text:
How should you arrange your chairs?
You teach a class of students with interesting preferences for how their chairs are arranged. There are 3 very specific requirements they have for how the chairs are arranged:

They most be arranged in a rectangle, even if it means some chairs go empty.

There must be as few empty chairs as possible.

They must be as "squarey" as possible. Squarey-ness is determined by the distance between the width and the height of the rectangle, lower is better. For example, a rectangle that is 4x7 has a squarey-ness of 3.

To be more specific, the "score" of an arrangement is the distance between the width and height plus the number of chairs that would go empty.
Let's take an example. Let's say you have 13 students. You could arrange the chairs any of these ways:
1x13
2x7
3x5
4x4

1x13 is not very squarey. In fact, 1 and 13 are 12 apart, so we give this arrangement 12 points. It also has 0 empty chairs, so we add 0 points, giving this arrangement a score of 12. Not that great.
2x7 is certainly better. 2 and 7 are only 5 apart, so we give this arrangement 5 points. However, if you actually arranged 2 rows of seven chairs, that would take 14 chairs, meaning one chair would be empty. So we add one point, giving this arrangement a score of 6.
We could also do 3x5. 3 and 5 are 2 apart, so +2 points. It takes 15 chairs, meaning we'd have two extra chairs, so another +2 points, for a score of 4.
Last option, 4x4. 4 and 4 are 0 apart, so we give this +0 points. 4x4 takes 16 chairs, so 3 chairs go empty, for a total score of 3. This is the optimal solution.
In case of a tie, the optimal solution is the one with less empty chairs.
The challenge
You must write a program or function that takes an integer and outputs the optimal arrangement of chairs for that number of students. IO can be in any reasonable format. Here is sample output for any number of students from 1 to 100:
1:  (1, 1)
2:  (1, 2)
3:  (2, 2)
4:  (2, 2)
5:  (2, 3)
6:  (2, 3)
7:  (3, 3)
8:  (3, 3)
9:  (3, 3)
10: (2, 5)
11: (3, 4)
12: (3, 4)
13: (4, 4)
14: (4, 4)
15: (4, 4)
16: (4, 4)
17: (3, 6)
18: (3, 6)
19: (4, 5)
20: (4, 5)
21: (3, 7)
22: (5, 5)
23: (5, 5)
24: (5, 5)
25: (5, 5)
26: (4, 7)
27: (4, 7)
28: (4, 7)
29: (5, 6)
30: (5, 6)
31: (4, 8)
32: (4, 8)
33: (6, 6)
34: (6, 6)
35: (6, 6)
36: (6, 6)
37: (5, 8)
38: (5, 8)
39: (5, 8)
40: (5, 8)
41: (6, 7)
42: (6, 7)
43: (5, 9)
44: (5, 9)
45: (5, 9)
46: (7, 7)
47: (7, 7)
48: (7, 7)
49: (7, 7)
50: (5, 10)
51: (6, 9)
52: (6, 9)
53: (6, 9)
54: (6, 9)
55: (7, 8)
56: (7, 8)
57: (6, 10)
58: (6, 10)
59: (6, 10)
60: (6, 10)
61: (8, 8)
62: (8, 8)
63: (8, 8)
64: (8, 8)
65: (6, 11)
66: (6, 11)
67: (7, 10)
68: (7, 10)
69: (7, 10)
70: (7, 10)
71: (8, 9)
72: (8, 9)
73: (7, 11)
74: (7, 11)
75: (7, 11)
76: (7, 11)
77: (7, 11)
78: (9, 9)
79: (9, 9)
80: (9, 9)
81: (9, 9)
82: (7, 12)
83: (7, 12)
84: (7, 12)
85: (8, 11)
86: (8, 11)
87: (8, 11)
88: (8, 11)
89: (9, 10)
90: (9, 10)
91: (7, 13)
92: (8, 12)
93: (8, 12)
94: (8, 12)
95: (8, 12)
96: (8, 12)
97: (10, 10)
98: (10, 10)
99: (10, 10)
100: (10, 10)

As usual, this is code-golf, so standard loopholes apply, and the winner is the shortest answer in bytes.

Related.

Jelly, 16 15 14 bytes
÷RĊ,Rµạ/+PỤḢịZ

Try it online! or verify all test cases.
How it works
÷RĊ,Rµạ/+PỤḢịZ  Main link. Argument: n

 R              Range; yield [1, ..., n].
÷               Divide n by each k in [1, ..., n].
  Ċ             Ceil; round the quotients up to the nearest integer.
    R           Range; yield [1, ..., n].
   ,            Pair; yield A := [[ ⌈n ÷ 1⌉, ..., ⌈n ÷ n⌉ ], [ 1, ..., n ]].
     µ          Begin a new, monadic chain. Argument: A
      ạ/        Reduce A by absolute difference.
                This yields [ |⌈n ÷ 1⌉ - 1|, ..., |⌈n ÷ n⌉ - n| ].
         P      Product; reduce A by multiplication.
                This yields [ ⌈n ÷ 1⌉ × 1, ..., ⌈n ÷ n⌉ × n].
       +        Add the results to left and right, element by element. This yields
                [ |⌈n ÷ 1⌉ - 1| + ⌈n ÷ 1⌉ × 1, ..., |⌈n ÷ n⌉ - n| + ⌈n ÷ n⌉ × n ].
          Ụ     Grade up; sort the indices of the list of sums by their values.
           Ḣ    Head; extract the first value, which corresponds to the smallest
                sum. Grading up is stable, so this selects the first index of all
                with the smallest sum in case of a tie. In this event, the first
                index will have the highest absolute difference of all indices
                with the smallest sum, meaning that it has the lowest product and,
                therefore, the lowest number of empty chairs.
             Z  Zip; transpose A's rows and columns.
                This yields [[ ⌈n ÷ 1⌉, 1 ], ..., [ ⌈n ÷ n⌉, n ]].
            ị   Retrieve the pair at that index.

Python 2, 68 bytes
lambda n:min((abs(~i-n/~i)+n/~i*~i,i+1,0-n/~i)for i in range(n))[1:]

Equivalent to the more “obvious”:
lambda n:min([(i+1,0-n/~i)for i in range(n)],key=lambda(p,q):abs(p-q)+p*q)

You can save three bytes by iterating over range(-n,0), like I do in my answer. Test suite.

Haskell, 65 bytes
f x=snd$minimum[((a*b+a-b,a*b),(b,a))|a<-[1..x],b<-[1..a],a*b>=x]

Usage example: map f [1..5] -> [(1,1),(1,2),(2,2),(2,2),(2,3)].
Goes through an outer loop a from 1 to x (x -> number of students) and an inner loop b from 1 to a. Keeps all (b,a) where a*b>=x and builds pairs of ((arrangement points,seats left), (b,a)) which follow the lexicographical order we need to find the minimum. Note: a is always greater than b, so we don't need abs for squareyness. No need to subtract x from the "seats left" score, because only the relative order matters. Finally we remove the score pair with snd.

Why not just (ab+a-b, (b, a))? If you minimise the score, surely you minimise ab anyway, or am I missing something?

@jpcooper: a*b (number of free seats) is the tie breaker if the main score is equal. E.g. n=43: a) a=7, b=7, score: (49,49) b) a=9, b=5, score: (49,45). Main score is equal, tie breaker decides,  b) wins.

You're right. I should have read the description better.

@jpcooper: wait a minute ... if I remove the tie breaker a*b, the numbers itself (b,a) which I have to carry around anyway act as the tie breaker and give the same results for (at least) n=1..300. A product is small if one of the factors (here b) is small. But as long as I have no formal proof, I don't want to use this fact. Let's see if I find one.

Good point. It seems right, and shouldn't be too hard to come up with a proof. I'm beginning to wonder though whether there might be a linear solution to this problem.

Javascript, 98 bytes
My first code golf, so I post anyway!
f=n=>{for(o=1/0,i=1;i<=n;i++)for(j=n;i*j>=n;j--)t=i*j-n+Math.abs(i-j),o>t&&(o=t,a=[i,j]);return a}

Initially my o was an empty object and I checked if o.a was empty, so it was a special case at the first round. But I found the 1/0 trick in edc65's answer to initialize the variable to Infinity.

And I'll try the trick to use an object to store the temporary result

MATL, 18 bytes
:Gy/Xkvtd|yp+&X<Z)

Try it online!
Explanation
:      % Implicit input number N. Range [1 2 ... N]
G      % Push N again
y      % Duplicate second-from-top: push [1 2 ... N] again
/Xk    % Divide and round up
v      % Vertically concatenate. Gives 2×N array of rectangle sizes
td|    % Duplicate. Absolute difference of each column
y      % Duplicate second-from-top: push 2×N array again
p      % Product of each column
+      % Sum absolute differences and products
&X<    % Arg min
Z)     % Use as column index into the 2×N array. Implicitly display

Ruby, 64 bytes
->n{(1..n).map{|w|h=(n+w-1)/w;[(h-w).abs+h*w,w*h,w,h]}.min[2,3]}

A lambada that takes the number of people as an argument and returns an array with width and height of the optimal solution.

Why do you need w*h as the second element in your array? I don't think it particularly changes anything when you call min because you minimize on the score aka the first element.

@KevinLau-notKenny from the question: In case of a tie, the optimal solution is the one with less empty chairs

Pyth, 24 22 21 bytes
Edit: in the sorting key, I realize that there is no need to find the number of empty chairs. It is equivalent to score the total number of chairs. This saved me 2 bytes.
h.m_+B*FbaFbm,d.EcQdS

Try it online!

Matlab(174)(146)121
  function g(n),f=@(n,i)ceil(n/i);x=[];for i=1:n,x=[sortrows(x); f(n,i)*i-1/(f(n,i)*i)+abs(f(n,i)-i) i f(n,i)];end,x(1,2:3)

trick 1: i added the amount 1-1/length*width as tie-scoring

trick 2: i calculated number_students/length ceiled for the width of rectangle, upper bound is the square but ceiled too

I'm sure it can be golfed further ...

try it

Edit : referenced to @StewieGriffin 's remarks .
Edit 2 :

1 and n are constants no need to add 'em to the overall score.
A function is few bytes less than stdin standalone program.
I used ascendent sorting technique it saves too much bytes though.

Edit 3: peformance test.

@StewieGriffin that is not big issue, it can be solved using unique

i think im halfway to some nice mathematical translation for this problem, but still it remains as conjecture

Also thought about this. See julia example.

JavaScript (ES6) 74 78
Edit keeping the temp result as an array instead of 2 vars, borrowed from Thiht's answer
n=>(z=>{for(x=0;y=-~(~-n/++x),x<=y;)(s=y-x+x*y-n)>=z||(z=s,r=[x,y])})()||r

Less golfed
n=>{
  z = 1/0
  for (x=0; y=(n-1)/++x+1|0, x <= y; )
  {
    s = y-x+x*y-n;
    if (s<z)
      z=s, r=[x,y]
  }
  return r
}

Test

f=n=>(z=>{for(x=0;y=-~(~-n/++x),x<=y;)(s=y-x+x*y-n)>=z||(z=s,r=[x,y])})()||r

out=x=>O.textContent+=x+'\n'

for(i=1;i<=100;i++)out(i+' :( '+f(i)+' )')

Julia, 61 59 55 53 52 bytes
/ =cld
n->[m=indmax([~i*~-max(i,n/i)for i=1:n]),n/m]

Try it online!
How it works
The code is equivalent to the following, ungolfed version, where cld is ceiling division.
function chairs(n)
    m = indmin([(i + 1) * (max(i, cld(n, i)) - 1) for i in 1:n])
    return [m, cld(n, m)]
end

To find the optimal arrangement, it is clearly sufficient to examine the pairs [i, j], where 1 ≤ i ≤ n and j = ⌈n / i⌉.
The score for such an arrangement is |j - i| + (ij - n), where the second summand is the number of empty chairs. Instead of the actual scores, we can compare scores augmented by a constant, such as ij + |j - i| + 1.
It is sufficient to consider pairs [i, j] where i ≤ j since the arrangements [i, j] and [j, i] are equally valid. We deal with strictly descending pairs by setting j = max(⌈n / i⌉, i) instead, which makes sure that j ≥ i and will yield a suboptimal score if ⌈n / i⌉ < i.
Since j - i ≥ 0, we have ij + |j - i| + 1 = ij + j - i + 1 = (i + 1) × (j - 1), which can be computed in fewer bytes of code.
Finally indmin / indmax gives the index m (and thus the value of i) of the optimal arrangement, which is m by ⌈n / m⌉. Ties are broken by first occurrence, which corresponds to the lowest value of i, therefore the highest value of j - i and thus the lowest value of ij - n (empty chairs).

Python 2, 64 bytes
lambda n:max((~-i*~min(i,n/i),0-n/i,-i)for i in range(-n,0))[1:]

This is an amalgamation of @Lynn's Python answer (from where I took the max(...)[1:] trick) and the algorithm from my Julia answer (which allows a slightly shorter implementation).
Test it on Ideone.

PHP, 129 bytes
function f($i){$s=INF;for($x=1;$x<$i;$x++){if($s>$t=(abs($x-$e=ceil($i/$x))-$i+($e*$x))){$s=$t;$d[0]=$x;$d[1]=$e;}}var_dump($d);}

Ungolfed:
function f ($i){
    $s=INF;
    for($x=1; $x<$i; $x++){ // for every number less than the input
        if( $s > $t=( abs($x-$e=ceil($i/$x))-$i+($e*$x) ) ){
            // determine the other dimension, the score, and compare to the minimum score
            $s=$t;
            $d[0]=$x;
            $d[1]=$e;
        }
    }
    var_dump($d);
}

PHP, 104 bytes
The algorithm that solves this problem is simple and it is probably used by other answers in languages similar to PHP (JavaScript, f.e.):

start with a large value for the initial score; n is large enough (where n is the input value); the score of the arrangement computed on the first iteration (1, n) is (n-1)+0;
iterate for all values of width between 1 and n; compute the minimum height as ceil(n/width), compute the arrangement score using the formula provided in the question (i.e. abs(width - height) + (width * height - n)); if the score is better than the previous best score then remember the width, the height and the new best score; on ties use the value of width * height - n for current arrangement and previous best arrangement to detect the new best arrangement;
that's all.

After golfing, this algorithm produces something like this (wrapped here for readability):
for($s=$h=$j=$n=$argv[$w=$i=1];$i<=$j;$j=ceil($n/++$i)
{$c=$j-$i+$i*$j-$n;if($c<$s||$c==$s&&$i*$j<$w*$h){$w=$i;$h=$j;$s=$c;}}
echo"$w,$h";

It uses 137 bytes (when put on a single line) and it is far from the 104 bytes advertised in the title. The code can probably be shortened by another 2-3 bytes but the big source of improvement is somewhere else: in the details of the algorithm.
The revised algorithm:
There are several places where the algorithm can be improved by removing useless code.

there is no need to iterate the width from 1 to $n; for speed, the width ($i) must iterate between 1 and floor(sqrt($n)) but this makes the code even longer instead of shortening it; but if the width doesn't exceed sqrt($n), the minimum height ($j) will always be larger than sqrt($n) (their product must be at least $n);
the previous statement allows using $i <= $j (width <= height) as the termination condition for loop; this way, the width will iterate from 1 to floor(sqrt($n)) and the height will get values starting with $n and going down to ceil(sqrt($n)) (not necessarily all of them);
knowing that width is always smaller than or equal to the height allow us know that abs(width - height) is always height - width ($j-$i); 5 bytes saved this way;
the input value $n is used in the computation of score (the number of unoccupied seats is width * height - n) but it is not needed; the score does not need to be displayed, it is computed only for comparison of the arrangements; by removing - n from the score formula we save another 3 bytes (the PHP code is -$n) without losing anything;
given the last two statements, the score formula becomes height - width + width * height ($j-$i+$i*$j);
on ties (the score of the current arrangement is the same as the previous best score), the rules say to use the arrangement with less free seats; because width always increases and height always decreases, the height - width part of the score decreases on each step;
if the current score is equal with the previous best score, the previous statements tells us that the number of free seats of the current arrangement is larger than the one of the previous best arrangement; this means the previous best arrangement win the tie;
because the ties are always won by the previous best arrangement, a new arrangement becomes the new best arrangement only when its score is smaller than the previous best; the code that checks for ties is useless and can be removed (||$c==$s&&$i*$j<$w*$h -- a lot of bytes);
because of the removal of -$n from the score's formula, the score for the first arrangement (1x$n) is $n-1+1*$n (i.e. 2*$n-1); the initial value of the best score ($s) can be any value greater than or equal to 2*$n; the first iteration has a better score and it becomes the best arrangement letting the algorithm run without initialization problems.

The new code (104 bytes), after applying the improvements described above is:
for($s=2*$j=$n=$argv[$i=1];$i<=$j;$j=ceil($n/++$i))
if($s>$c=$j-$i+$i*$j){$w=$i;$h=$j;$s=$c;}echo"$w,$h";

It is wrapped here for readability. Prepend the code above with the PHP marker <?php (technically, it is not part of the code), put it into a file (let's say arrange-your-chairs.php) and run it with an integer greater than zero as argument. It will display the width and height of the computed arrangement, separated by comma:
$ php arrange-your-chairs.php 1001
28,36

Another solution (116 bytes)
Another solution that uses a different algorithm:
for($n=$argv[1];++$j<=$n;)for($i=0;++$i<=$j;)
if($n<=$k=$i*$j)$a["$i,$j"]=($j-$i+$k-$n)*$n+$k;asort($a);echo key($a);

It puts all the combinations of at least $n seats into an associative list; the key is the text representation of the arrangement, the value is the arrangement's score. It then sorts the list (ascending by value) and gets the key of the first entry.
One more (115 bytes)
foreach(range(1,$m=$n=$argv[1])as$i)
if(($d=ceil($n/$i))<=$i&&$m>=$s=$i*$d-$n+$i-$d){$m=$s;$w=$d;$h=$i;}echo"$w,$h";

This is the PHP version of @Neil's answer (JavaScript/ES6, 85 bytes).
There are some noticeable differences due to the features of each language:

the JS answer generates an array of n (undefined) values then uses its keys to iterate from 0 to n-1; it increments i (d=(n+i++)/i|0) to make it iterate from 1 to n; the PHP solution doesn't need to increment; it uses range() to generate an array then it uses the generated values (1 to n) to iterate;
the JS answer uses (n+i)/i then converts the value to integer using |0 to get the smallest integer larger than n/i; the PHP answer solves this issue easily with the PHP function ceil(); JavaScript also provides Math.ceil() but it uses 5 bytes more than the solution found by Neil;
PHP provides the function array_map() that is somehow similar with JS Array.map() but it doesn't help here; its syntax is verbose, a foreach produces shorter code; it is larger than the JS code, though;
merging the assignments into the conditions using || is not possible in PHP because it lacks the comma operator; I translated a||b||c into if(!a&&!b)c then, because a and b are comparisons, I negated their operators (replaced < with >=); this also produces larger code than the JS version;
another 23 bytes have to be added just because the names of variables in PHP have to be prefixed by $.

The ungolfed versions of all solutions and the test suite can be found on Github.

This is the most thorough code-golf answer I have ever seen.

JavaSCript (ES6), 83 bytes
n=>[...Array(m=n)].map((_,i)=>(d=(n+i++)/i|0)>i||(s=i*d-n+i-d)>m||(m=s,r=[d,i]))&&r

Maybe you could apply my trick (to save 2 bytes)

@KennyLau I don't think it helps; I'd have to increase m to compensate.

Julia, 87
I think this is one step in direction towards finding a magic function for the problem:
f(i)=(i+n)÷(i+1)|>j->(j*i<n)+j
_=indmin([sqrt(n)<=i?i-f(i)*(1-i):2n for i=1:n])
_,f(_)

It only looks at pairs (i, j=(i+n)/(i+1)) or (i, j+1)

please explain further how does this work, you v turned me curious bout your function

I'm not sure how this is supposed to work. You don't define n anywhere, and you don't seem to be taking input.

Ah, sorry, I just took n as input. One would need to wrap it into n->.... Nice that you could make it work.

Oracle SQL 11.2, 173 bytes
SELECT MIN(x||','||y)KEEP(DENSE_RANK FIRST ORDER BY y-x+(y*x-:1))FROM(SELECT CEIL(LEVEL/:1)x,CEIL(MOD(LEVEL+.1,:1))y FROM DUAL CONNECT BY LEVEL<=:1*:1)WHERE x<=y AND:1<=x*y;

Un-golfed
SELECT MIN(x||','||y)KEEP(DENSE_RANK FIRST ORDER BY y-x+(y*x-:1))  -- Keeps the minimal score
FROM   (SELECT CEIL(LEVEL/:1)x,CEIL(MOD(LEVEL+.1,:1))y FROM DUAL CONNECT BY LEVEL<=:1*:1) -- Generate x,y combinations
WHERE  x<=y AND :1<=x*y  -- Filters out wrong combinations

Q 58 Bytes
{c@d?&/d:+/(-/;*/)@\:+c:{((b<a)?1b)#+(b:-_-x%a;a:1+!x)}x}

Lamba that calculates minimal cost for a given value (x) and returns a sequence of two values (width,height)
Adding name to that lambda requires other two char (ex f:{..} instead of {..})
Test
{..}'1+!100

where {..} is the lambda. Read as "applies lambda to each value of 1+first 100 ints" (in other words to each value 1..100)
Generates
1 1
2 1
2 2
2 2
3 2
3 2
3 3
3 3
3 3
5 2
4 3
4 3
4 4
4 4
4 4
4 4
6 3
6 3
5 4
5 4
7 3
5 5
..

Explanation
Nested lamdba {((b<a)?1b)#+(b:-_-x%a;a:1+!x)} generates all candidates (widht,height) pairs for x chairs as two sequences (w1 w2 w3 ..; h1 h2 h3 ..) (widths and heights). Read from left to right, but evaluates from right to left
a:1+!x generates values 1..x and assign that sequence to a
-_- is negate floor negate, and implements ceil (ceil is not a primitive of the language)
b:-_-x%a applies ceil to each value of x divided by any item im a, and assign the resulting sequence to b. In other words, b is ceil each x dividedBy each 1..x
+(b;a) return a secuence composed of seq a and seq b, an then flips it (the result is a sequence of pair where i-pair contains element i of a and element i of b)
b<a compares item by item of b and a, and generates a secuence of logical values (true=1b for each index where b[i]

s?x returns the first position of item x in sequence s. With (b<a)?1b We look for 1b (true value) in sequence resulting of compare b and a, and get first position where b

n#s takes n first n items from seq s. We want to discard duplicate pairs, so we stop when first item of a pair < second item (ex. consider 13,1 but not 1,13).
As a side effect, each pair of the resulting sequence are of decreasing distance between a and b (ex (13 1; 7 2; 5 3; 4 4)
The candidate pair generated by nested lambda are assigned to c. We then flip c (obtains b,a again) and applies two functions to that argument: */ multiplies over, and -/ subtract over. The result of (-/;*/)@\:+c is the difference and product of each pair. +/ is sum over, and calculares final cost. The cost of each patir is assigned to d
&/ is minimum over, so &/d is the minimum cost. With d?&/d we find the first occurrence of minimum cost in d, and with c@.. we retrieve the pair at that position. As each pair is of decreasing distante between a and n, the first minimum found has the maximum distante betwwen other minimum pairs, so we apply tie rule correctly


text:
Restricted average (arithmetic mean) – i.e. without obvious built-ins
Introduction
The arithmetic mean is defined as being equal to the sum of the numerical values of each and every observation divided by the total number of observations. Symbolically, if we have a data set containing the values a1,…,an. The arithmetic mean A is defined by the formula

Objective
The challenge here is, given a non-empty list of observations, to calculate the arithmetic mean without any built-ins for mean, sum, division, or count. All other operations are allowed, e.g. median, product, multiplication, and sequence generation.
If your language cannot process lists without knowing the number of elements it has, you may use a counting built-in for such (looping, loading, etc.) purpose only, but not for the actual computation.
Test cases
[5] → 5
[1,-2] → -0.5
[6,1,3] → 3.333333333
If your language can handle complex numbers:
[5,1+3i] → 3+1.5i

This is a cut-and-dry Do X without Y challenge.

Possible duplicate of Operations with Lists

@Mego How can it be a dup if the other one isn't a Do X without Y?

The core challenge is the same, and the "without Y" part doesn't significantly distinguish it.

@Mego No the core here isn't list operations. It is alternative ways to do things.

If that were true, that would mean this is a chameleon challenge, which is similarly bad.

Compute the mean without even knowinf how many things there are? I don't even know if this is possible...

@Mego What? Isn't the title pretty clear?

What if my language can only handle integers?

@KennyLau It is. Possible? Why not? Other array/list operations are allowed.

Such as enumerate?

@KennyLau Then Either round/trunc/floor to int and/or use sample input that is 1000 times bigger!

@KennyLau If "enumerate" means generating the indices of the list then, yes, max(enumerate(input)) would give you the length.

If I only use string manipulations to do that? (Further question of the "what if I only use integers")

@KennyLau Again, only 1. mean, 2. sum, 3. division, and 4. counting are prohibited. E.g. median, product, multiplication, and sequence generation are all permitted.

@Mego Can you explain why this is unclear. You may dislike this (type of) question, but what is unclear about it?

I did not vote to close as unclear - I voted to close as duplicate.

@Mego Huh?! so why does the system say put on hold as unclear what you're asking by Mego, xnor, ...?

The on hold message shows the close reason that the majority of the close voters chose.

Does evaluating an array as a scalar (which yields its count in Perl) count as using a built-in for count?

Pyth, 13 bytes
l@*F^L2Qhe.ek

Try it online!
Uses exponential arithmetic to replace sum and division.
Uses enumerate to find number of elements.

Perfect, that's the type of substitutions I had in mid.

Retina, 46 37 bytes

+`x;
;x
;x
;;:x
;
x
^(x+):(\1)*x*
$#2

Try it online!
It's quite a trouble not to use arithmetic...

source: Stack Exchange

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

sort: votes


text:
Generate ASCII TetraVex
TetraVex is a tile-based edge-matching game that was originally coded by Scott Ferguson for the Microsoft Entertainment Pack 3 back in 1990. The game consists of a grid upon which square tiles are placed. The tiles have numbers or letters on each edge, and the goal is to place all tiles in the grid, with each pair of edges matching, in the fastest time. Since solving TetraVex is known to be NP-Complete, we're instead just going to generate a solved board.
For our purposes, each TetraVex tile is 5 characters wide by 3 tall, and follows the pattern:
\ # /
# X #
/ # \

where each # is replaced with an alphanumeric symbol matching [A-Z0-9] (capitals, not lowercase).
When placed on the board, the tiles have additional spaces between them on the grid, in order to differentiate the tiles horizontally from each other. The grid is composed of |, -, and + symbols, as shown below. Note that there is no border on the outside of the gameplay area, and no trailing spaces to the right of the tiles.
\ # / | \ # /
# X # | # X #
/ # \ | / # \
------+------
\ # / | \ # /
# X # | # X #
/ # \ | / # \

Input

Two integers 1 < n,m <= 255 in any convenient format (tuple, array, function argument, etc.). The numbers can be taken in either order (please specify in your answer which order).
These represent a board of n tiles wide by m tiles tall.

The smallest board output will thus be 2x2 tiles, or 13 characters wide by 7 characters tall.
The largest is 255x255 tiles, or 2037 characters wide by 1019 characters tall.

Output

An ASCII representation of a TetraVex board of size n x m.
The board must follow the tile construction rules above, and must be a solved board (meaning the paired edges match). Non-paired edges (i.e., the border) can be any legal character.

Rules

Each individual tile in the output must be unique.

Reflected or rotated tiles count as distinct, since during actual gameplay you're not permitted to rotate or flip the tiles in any manner.
For example, a tile with 1 A on top and 3 Bs on the other edges is considered distinct from a tile with 1 A on the right and 3 Bs on the other edges.

The output must be somewhat non-deterministic, meaning different runs of the code with the same n and m input should yield different boards. However, in the interests of complexity, not all possible n x m boards need have non-zero probability in your output -- only at least two of the possible boards must have non-zero probability of actually being produced.

For example, a 3 x 3 board, with full alphanumeric edges, already has somewhere around 36^24 ~= 2.25e37 possible boards. Since that number grows exponentially as the size increases, ensuring equal probability for all boards may become infeasible for many languages.
This does mean you could have two separate deterministic code paths produce two separate boards and then simply flip a coin to determine which to output -- that's fine. (For example, starting with the first tile all A in one path and all B in the other, and then generate the rest of the board using the same algorithm from there will guarantee two unique boards and is allowed)
Any of our usual definitions for randomness will suffice for determining this non-zero probability.
Rotations or reflections of the board are considered "different" boards, but note that you're not guaranteed a square grid, only a rectangular one. ;-)
Generating a board and then replacing a certain character with another (e.g., replacing all A with Z) is allowed, provided that each tile in the output is still unique.

Trailing spaces are not allowed but trailing newline(s) are OK.
Standard loopholes are forbidden.
This is code-golf, so all usual golfing rules apply, and the shortest code wins.

Examples
1) Input: 3 3
\ A / | \ B / | \ C /
D X E | E X G | G X I
/ J \ | / K \ | / L \
------+-------+------
\ J / | \ K / | \ L /
M X N | N X O | O X P
/ Q \ | / R \ | / S \
------+-------+------
\ Q / | \ R / | \ S /
T X U | U X V | V X W
/ X \ | / Y \ | / Z \

2) Input: 5 3
\ 0 / | \ B / | \ C / | \ A / | \ Z /
D X E | E X F | F X I | I X A | A X Q
/ J \ | / 9 \ | / L \ | / L \ | / 6 \
------+-------+-------+-------+------
\ J / | \ 9 / | \ L / | \ L / | \ 6 /
M X N | N X 4 | 4 X P | P X P | P X T
/ R \ | / R \ | / S \ | / B \ | / K \
------+-------+-------+-------+------
\ R / | \ R / | \ S / | \ B / | \ K /
T X Z | Z X V | V X W | W X J | J X G
/ X \ | / Y \ | / Z \ | / X \ | / A \

Can I output a board where all the #s are A?

@Kenny: Each individual tile in the output must be unique.

1.Are rotations and reflections of tiles considered unique? 2.Are rotations and reflections of boards considered unique (eg is it sufficient to generate one board deterministically and turn it upside down at random?) 3. Are relabellings of boards unique (if I change ALL the A's to Z's, is that the same board or a different one?)

@LevelRiverSt asked about tiles, too. Are "\\ A /\nB X C\n/ D \\" and "\\ B /\nD X A\n/ C \\" the same tile?

Grid is still guaranteed to be rectangular, though. So it can be reflected horizontally, vertically, or (most similarly) rotated 180 degrees. Are they considered the same?

@Lynn Tile rotations/reflections aren't a problem, since you're not allowed to rotate or flip the tiles when you're actually playing the game -- I'll clarify that.

@LevelRiverSt I see what you're saying. Reconsidering, I'll allow the full reflection/rotation spectrum.

r.tr!'ab','ba'if rand>.5 is perfectly legit you say?

@JanDvorak If you can still guarantee a solved board and that every tile is unique, go for it.

Happy coincidence: My own question Output diagonal positions of me squared has the same pattern as example!

CJam, 116
26mr:D;q~:B;){[7B),f#10222@#f*2G#)f%_2ew:+23f%\W<26f%]{D+26%'A+}f%~"\/"f*_:$@2/'Xf*[@]'|f*Sf*~_'{f>"-+"f=\@}%2>-3<N*

Try it online
Uses only letters.
Explanation:
The first observation is that any rectangular piece of a solved board is a solved board. Since the program needs to work up to 255×255, it is enough to solve it for that case and use a piece of that board with the requested dimensions.
I am using a fixed 255×255 board that I determined to be correct. I actually did 256×256 tiles first, choosing 2 numbers per tile (top and left), then copied the other numbers from adjacent tiles, discarding some edge numbers from the last row and last column.
Each tile is first given an associated number, and then I calculate the remainders of that number modulo two other numbers (I used 23 and 26) to get the 2 numbers chosen for that tile.
In order to avoid patterns which lead to duplication, I decided to make the associated numbers pseudo-random and unique. I used my favorite distinct not-very-random number generator, which is based on primitive roots: take a prime number slightly bigger than the desired range (65537) and a small prime number (7), then use the powers of the small number modulo the big number. After a few trials, I found that the combination of 7, 23 and 26 works well, giving 65025 (255²) unique tiles.
For the random factor, I am just applying a random cyclic permutation to the value of each number. Then the numbers (0-25) are converted to letters (A-Z).
Code explanation to follow.

Ruby 196
This is an anonymous function that takes width and length as arguments and writes to stdout.
->m,n{r=rand(9)
t=""
128.times{|h|t<<"%02X"%((h+r)*17%256)}
(m*n*4-m).times{|k|i=k%m;j=k/m
s="\\ #{t[j/4]} / | #{t[i]} X #{t[i+1]} | / #{t[j/4+1]} \\ | ------+-"[j%4*8,8]
i==m-1&&s[5,3]=$/
$><<s}}

Explanation
Uniqueness of cells is guaranteed by having the contents of each cell correspond to its x,y coordinates, as below. As a result the pattern is always symmetrical about the NW-SE diagonal:
00,00 01,00 02,00 03,00 04,00 05,00 06,00 07,00 08,00 09,00 10,00 11,00...
00,01 01,01 02,01 03,01 04,01 05,01 06,01 07,01 08,01 09,01 10,00 11,01...
00,00 01,02 02,02 03,02 04,02 05,02 06,02 07,02 08,02 09,02 10,02 11,02...
.
etc

The x values appear on the left and right edges of the tile, and the y values on  the top and bottom edges.
The astute will have noticed that we cannot simply write a 2-digit number across each tile, because the edges will not match. What is needed is a sequence of (at least) 255 digits where all combinations are unique. From this we can pick a pair of digits (e.g. 1 and 2) for the first tile , then follow naturally on to the next, where the last number of one tile becomes the first of the next (e.g. 2 and 3).
I use a sequence containing just the hexadecimal digits 0-9A-F because the hexadecimal number representation is more golfable than some other arbitrary base. Therefore I need a 256 digit sequence where every one of the possible 2-digit combinations appears exactly once. Such a sequence is known as a De Bruijn sequence.
I have discovered a very golfy way of generating De Bruijn sequences of subsequence length 2 with digits from even base numbers. We simply take all the numbers from 0 to b*b/2-1, multiply them by b+1,take the last 2 digits, and concatenate the results. Here is an illustration of the sequence used with a bit more explanation as to how it works for base b=16. Basically each line contains all combinations with two of the possible differences between digits, which together add up to 1 or 17 (mod 16). It is necessary to think in modular base 16 arithmetic, where for example -1 = +F.
00112233445566778899AABBCCDDEEFF Difference between digits is +1 or +0
102132435465768798A9BACBDCEDFE0F Difference between digits is +2 or +F
2031425364758697A8B9CADBECFD0E1F Difference between digits is +3 or +E
30415263748596A7B8C9DAEBFC0D1E2F     .         .       .       .     .
405162738495A6B7C8D9EAFB0C1D2E3F     .         .       .       .     .
5061728394A5B6C7D8E9FA0B1C2D3E4F     .         .       .       .     .
60718293A4B5C6D7E8F90A1B2C3D4E5F Difference between digits is +7 or +A
708192A3B4C5D6E7F8091A2B3C4D5E6F Difference between digits is +8 or +9

Finally, to comply with the random requirement, the pattern can be shifted diagonally by a random number 0..8 so there are 9 possible boards that can be generated.
ungolfed in test program
f=->m,n{                               #width,height

r=rand(9)                              #pick a random number

t=""                                   #setup empty string and build a DeBruijn sequence
128.times{|h|t<<"%02X"%((h+r)*17%256)} #with all 2-digit combinations of 0-9A-F

(m*n*4-m).times{|k|                    #loop enough for rows*columns, 4 rows per tile, omitting last row.
i=k%m;j=k/m                            #i and j are the x and y coordinates
                                       #lookup the 4 values for the current tile and select the appropriate 8-character segment
                                       # from the 32-character string produced, according to the row of the tile we are on.
s="\\ #{t[j/4]} / | #{t[i]} X #{t[i+1]} | / #{t[j/4+1]} \\ | ------+-"[j%4*8,8]
i==m-1&&s[5,3]=$/                      #if i is on the rightmost row, delete the last 3 charaters of s and replace with \n
$><<s}}                                #print the current horizontal segment of the current tile.

f[20,20]

Output for 20,20 where r=8
\ 8 / | \ 8 / | \ 8 / | \ 8 / | \ 8 / | \ 8 / | \ 8 / | \ 8 / | \ 8 / | \ 8 / | \ 8 / | \ 8 / | \ 8 / | \ 8 / | \ 8 / | \ 8 / | \ 8 / | \ 8 / | \ 8 / | \ 8 /
8 X 8 | 8 X 9 | 9 X 9 | 9 X A | A X A | A X B | B X B | B X C | C X C | C X D | D X D | D X E | E X E | E X F | F X F | F X 1 | 1 X 0 | 0 X 2 | 2 X 1 | 1 X 3
/ 8 \ | / 8 \ | / 8 \ | / 8 \ | / 8 \ | / 8 \ | / 8 \ | / 8 \ | / 8 \ | / 8 \ | / 8 \ | / 8 \ | / 8 \ | / 8 \ | / 8 \ | / 8 \ | / 8 \ | / 8 \ | / 8 \ | / 8 \
------+-------+-------+-------+-------+-------+-------+-------+-------+-------+-------+-------+-------+-------+-------+-------+-------+-------+-------+------
\ 8 / | \ 8 / | \ 8 / | \ 8 / | \ 8 / | \ 8 / | \ 8 / | \ 8 / | \ 8 / | \ 8 / | \ 8 / | \ 8 / | \ 8 / | \ 8 / | \ 8 / | \ 8 / | \ 8 / | \ 8 / | \ 8 / | \ 8 /
8 X 8 | 8 X 9 | 9 X 9 | 9 X A | A X A | A X B | B X B | B X C | C X C | C X D | D X D | D X E | E X E | E X F | F X F | F X 1 | 1 X 0 | 0 X 2 | 2 X 1 | 1 X 3
/ 9 \ | / 9 \ | / 9 \ | / 9 \ | / 9 \ | / 9 \ | / 9 \ | / 9 \ | / 9 \ | / 9 \ | / 9 \ | / 9 \ | / 9 \ | / 9 \ | / 9 \ | / 9 \ | / 9 \ | / 9 \ | / 9 \ | / 9 \
------+-------+-------+-------+-------+-------+-------+-------+-------+-------+-------+-------+-------+-------+-------+-------+-------+-------+-------+------
\ 9 / | \ 9 / | \ 9 / | \ 9 / | \ 9 / | \ 9 / | \ 9 / | \ 9 / | \ 9 / | \ 9 / | \ 9 / | \ 9 / | \ 9 / | \ 9 / | \ 9 / | \ 9 / | \ 9 / | \ 9 / | \ 9 / | \ 9 /
8 X 8 | 8 X 9 | 9 X 9 | 9 X A | A X A | A X B | B X B | B X C | C X C | C X D | D X D | D X E | E X E | E X F | F X F | F X 1 | 1 X 0 | 0 X 2 | 2 X 1 | 1 X 3
/ 9 \ | / 9 \ | / 9 \ | / 9 \ | / 9 \ | / 9 \ | / 9 \ | / 9 \ | / 9 \ | / 9 \ | / 9 \ | / 9 \ | / 9 \ | / 9 \ | / 9 \ | / 9 \ | / 9 \ | / 9 \ | / 9 \ | / 9 \
------+-------+-------+-------+-------+-------+-------+-------+-------+-------+-------+-------+-------+-------+-------+-------+-------+-------+-------+------
\ 9 / | \ 9 / | \ 9 / | \ 9 / | \ 9 / | \ 9 / | \ 9 / | \ 9 / | \ 9 / | \ 9 / | \ 9 / | \ 9 / | \ 9 / | \ 9 / | \ 9 / | \ 9 / | \ 9 / | \ 9 / | \ 9 / | \ 9 /
8 X 8 | 8 X 9 | 9 X 9 | 9 X A | A X A | A X B | B X B | B X C | C X C | C X D | D X D | D X E | E X E | E X F | F X F | F X 1 | 1 X 0 | 0 X 2 | 2 X 1 | 1 X 3
/ A \ | / A \ | / A \ | / A \ | / A \ | / A \ | / A \ | / A \ | / A \ | / A \ | / A \ | / A \ | / A \ | / A \ | / A \ | / A \ | / A \ | / A \ | / A \ | / A \
------+-------+-------+-------+-------+-------+-------+-------+-------+-------+-------+-------+-------+-------+-------+-------+-------+-------+-------+------
\ A / | \ A / | \ A / | \ A / | \ A / | \ A / | \ A / | \ A / | \ A / | \ A / | \ A / | \ A / | \ A / | \ A / | \ A / | \ A / | \ A / | \ A / | \ A / | \ A /
8 X 8 | 8 X 9 | 9 X 9 | 9 X A | A X A | A X B | B X B | B X C | C X C | C X D | D X D | D X E | E X E | E X F | F X F | F X 1 | 1 X 0 | 0 X 2 | 2 X 1 | 1 X 3
/ A \ | / A \ | / A \ | / A \ | / A \ | / A \ | / A \ | / A \ | / A \ | / A \ | / A \ | / A \ | / A \ | / A \ | / A \ | / A \ | / A \ | / A \ | / A \ | / A \
------+-------+-------+-------+-------+-------+-------+-------+-------+-------+-------+-------+-------+-------+-------+-------+-------+-------+-------+------
\ A / | \ A / | \ A / | \ A / | \ A / | \ A / | \ A / | \ A / | \ A / | \ A / | \ A / | \ A / | \ A / | \ A / | \ A / | \ A / | \ A / | \ A / | \ A / | \ A /
8 X 8 | 8 X 9 | 9 X 9 | 9 X A | A X A | A X B | B X B | B X C | C X C | C X D | D X D | D X E | E X E | E X F | F X F | F X 1 | 1 X 0 | 0 X 2 | 2 X 1 | 1 X 3
/ B \ | / B \ | / B \ | / B \ | / B \ | / B \ | / B \ | / B \ | / B \ | / B \ | / B \ | / B \ | / B \ | / B \ | / B \ | / B \ | / B \ | / B \ | / B \ | / B \
------+-------+-------+-------+-------+-------+-------+-------+-------+-------+-------+-------+-------+-------+-------+-------+-------+-------+-------+------
\ B / | \ B / | \ B / | \ B / | \ B / | \ B / | \ B / | \ B / | \ B / | \ B / | \ B / | \ B / | \ B / | \ B / | \ B / | \ B / | \ B / | \ B / | \ B / | \ B /
8 X 8 | 8 X 9 | 9 X 9 | 9 X A | A X A | A X B | B X B | B X C | C X C | C X D | D X D | D X E | E X E | E X F | F X F | F X 1 | 1 X 0 | 0 X 2 | 2 X 1 | 1 X 3
/ B \ | / B \ | / B \ | / B \ | / B \ | / B \ | / B \ | / B \ | / B \ | / B \ | / B \ | / B \ | / B \ | / B \ | / B \ | / B \ | / B \ | / B \ | / B \ | / B \
------+-------+-------+-------+-------+-------+-------+-------+-------+-------+-------+-------+-------+-------+-------+-------+-------+-------+-------+------
\ B / | \ B / | \ B / | \ B / | \ B / | \ B / | \ B / | \ B / | \ B / | \ B / | \ B / | \ B / | \ B / | \ B / | \ B / | \ B / | \ B / | \ B / | \ B / | \ B /
8 X 8 | 8 X 9 | 9 X 9 | 9 X A | A X A | A X B | B X B | B X C | C X C | C X D | D X D | D X E | E X E | E X F | F X F | F X 1 | 1 X 0 | 0 X 2 | 2 X 1 | 1 X 3
/ C \ | / C \ | / C \ | / C \ | / C \ | / C \ | / C \ | / C \ | / C \ | / C \ | / C \ | / C \ | / C \ | / C \ | / C \ | / C \ | / C \ | / C \ | / C \ | / C \
------+-------+-------+-------+-------+-------+-------+-------+-------+-------+-------+-------+-------+-------+-------+-------+-------+-------+-------+------
\ C / | \ C / | \ C / | \ C / | \ C / | \ C / | \ C / | \ C / | \ C / | \ C / | \ C / | \ C / | \ C / | \ C / | \ C / | \ C / | \ C / | \ C / | \ C / | \ C /
8 X 8 | 8 X 9 | 9 X 9 | 9 X A | A X A | A X B | B X B | B X C | C X C | C X D | D X D | D X E | E X E | E X F | F X F | F X 1 | 1 X 0 | 0 X 2 | 2 X 1 | 1 X 3
/ C \ | / C \ | / C \ | / C \ | / C \ | / C \ | / C \ | / C \ | / C \ | / C \ | / C \ | / C \ | / C \ | / C \ | / C \ | / C \ | / C \ | / C \ | / C \ | / C \
------+-------+-------+-------+-------+-------+-------+-------+-------+-------+-------+-------+-------+-------+-------+-------+-------+-------+-------+------
\ C / | \ C / | \ C / | \ C / | \ C / | \ C / | \ C / | \ C / | \ C / | \ C / | \ C / | \ C / | \ C / | \ C / | \ C / | \ C / | \ C / | \ C / | \ C / | \ C /
8 X 8 | 8 X 9 | 9 X 9 | 9 X A | A X A | A X B | B X B | B X C | C X C | C X D | D X D | D X E | E X E | E X F | F X F | F X 1 | 1 X 0 | 0 X 2 | 2 X 1 | 1 X 3
/ D \ | / D \ | / D \ | / D \ | / D \ | / D \ | / D \ | / D \ | / D \ | / D \ | / D \ | / D \ | / D \ | / D \ | / D \ | / D \ | / D \ | / D \ | / D \ | / D \
------+-------+-------+-------+-------+-------+-------+-------+-------+-------+-------+-------+-------+-------+-------+-------+-------+-------+-------+------
\ D / | \ D / | \ D / | \ D / | \ D / | \ D / | \ D / | \ D / | \ D / | \ D / | \ D / | \ D / | \ D / | \ D / | \ D / | \ D / | \ D / | \ D / | \ D / | \ D /
8 X 8 | 8 X 9 | 9 X 9 | 9 X A | A X A | A X B | B X B | B X C | C X C | C X D | D X D | D X E | E X E | E X F | F X F | F X 1 | 1 X 0 | 0 X 2 | 2 X 1 | 1 X 3
/ D \ | / D \ | / D \ | / D \ | / D \ | / D \ | / D \ | / D \ | / D \ | / D \ | / D \ | / D \ | / D \ | / D \ | / D \ | / D \ | / D \ | / D \ | / D \ | / D \
------+-------+-------+-------+-------+-------+-------+-------+-------+-------+-------+-------+-------+-------+-------+-------+-------+-------+-------+------
\ D / | \ D / | \ D / | \ D / | \ D / | \ D / | \ D / | \ D / | \ D / | \ D / | \ D / | \ D / | \ D / | \ D / | \ D / | \ D / | \ D / | \ D / | \ D / | \ D /
8 X 8 | 8 X 9 | 9 X 9 | 9 X A | A X A | A X B | B X B | B X C | C X C | C X D | D X D | D X E | E X E | E X F | F X F | F X 1 | 1 X 0 | 0 X 2 | 2 X 1 | 1 X 3
/ E \ | / E \ | / E \ | / E \ | / E \ | / E \ | / E \ | / E \ | / E \ | / E \ | / E \ | / E \ | / E \ | / E \ | / E \ | / E \ | / E \ | / E \ | / E \ | / E \
------+-------+-------+-------+-------+-------+-------+-------+-------+-------+-------+-------+-------+-------+-------+-------+-------+-------+-------+------
\ E / | \ E / | \ E / | \ E / | \ E / | \ E / | \ E / | \ E / | \ E / | \ E / | \ E / | \ E / | \ E / | \ E / | \ E / | \ E / | \ E / | \ E / | \ E / | \ E /
8 X 8 | 8 X 9 | 9 X 9 | 9 X A | A X A | A X B | B X B | B X C | C X C | C X D | D X D | D X E | E X E | E X F | F X F | F X 1 | 1 X 0 | 0 X 2 | 2 X 1 | 1 X 3
/ E \ | / E \ | / E \ | / E \ | / E \ | / E \ | / E \ | / E \ | / E \ | / E \ | / E \ | / E \ | / E \ | / E \ | / E \ | / E \ | / E \ | / E \ | / E \ | / E \
------+-------+-------+-------+-------+-------+-------+-------+-------+-------+-------+-------+-------+-------+-------+-------+-------+-------+-------+------
\ E / | \ E / | \ E / | \ E / | \ E / | \ E / | \ E / | \ E / | \ E / | \ E / | \ E / | \ E / | \ E / | \ E / | \ E / | \ E / | \ E / | \ E / | \ E / | \ E /
8 X 8 | 8 X 9 | 9 X 9 | 9 X A | A X A | A X B | B X B | B X C | C X C | C X D | D X D | D X E | E X E | E X F | F X F | F X 1 | 1 X 0 | 0 X 2 | 2 X 1 | 1 X 3
/ F \ | / F \ | / F \ | / F \ | / F \ | / F \ | / F \ | / F \ | / F \ | / F \ | / F \ | / F \ | / F \ | / F \ | / F \ | / F \ | / F \ | / F \ | / F \ | / F \
------+-------+-------+-------+-------+-------+-------+-------+-------+-------+-------+-------+-------+-------+-------+-------+-------+-------+-------+------
\ F / | \ F / | \ F / | \ F / | \ F / | \ F / | \ F / | \ F / | \ F / | \ F / | \ F / | \ F / | \ F / | \ F / | \ F / | \ F / | \ F / | \ F / | \ F / | \ F /
8 X 8 | 8 X 9 | 9 X 9 | 9 X A | A X A | A X B | B X B | B X C | C X C | C X D | D X D | D X E | E X E | E X F | F X F | F X 1 | 1 X 0 | 0 X 2 | 2 X 1 | 1 X 3
/ F \ | / F \ | / F \ | / F \ | / F \ | / F \ | / F \ | / F \ | / F \ | / F \ | / F \ | / F \ | / F \ | / F \ | / F \ | / F \ | / F \ | / F \ | / F \ | / F \
------+-------+-------+-------+-------+-------+-------+-------+-------+-------+-------+-------+-------+-------+-------+-------+-------+-------+-------+------
\ F / | \ F / | \ F / | \ F / | \ F / | \ F / | \ F / | \ F / | \ F / | \ F / | \ F / | \ F / | \ F / | \ F / | \ F / | \ F / | \ F / | \ F / | \ F / | \ F /
8 X 8 | 8 X 9 | 9 X 9 | 9 X A | A X A | A X B | B X B | B X C | C X C | C X D | D X D | D X E | E X E | E X F | F X F | F X 1 | 1 X 0 | 0 X 2 | 2 X 1 | 1 X 3
/ 1 \ | / 1 \ | / 1 \ | / 1 \ | / 1 \ | / 1 \ | / 1 \ | / 1 \ | / 1 \ | / 1 \ | / 1 \ | / 1 \ | / 1 \ | / 1 \ | / 1 \ | / 1 \ | / 1 \ | / 1 \ | / 1 \ | / 1 \
------+-------+-------+-------+-------+-------+-------+-------+-------+-------+-------+-------+-------+-------+-------+-------+-------+-------+-------+------
\ 1 / | \ 1 / | \ 1 / | \ 1 / | \ 1 / | \ 1 / | \ 1 / | \ 1 / | \ 1 / | \ 1 / | \ 1 / | \ 1 / | \ 1 / | \ 1 / | \ 1 / | \ 1 / | \ 1 / | \ 1 / | \ 1 / | \ 1 /
8 X 8 | 8 X 9 | 9 X 9 | 9 X A | A X A | A X B | B X B | B X C | C X C | C X D | D X D | D X E | E X E | E X F | F X F | F X 1 | 1 X 0 | 0 X 2 | 2 X 1 | 1 X 3
/ 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 /
8 X 8 | 8 X 9 | 9 X 9 | 9 X A | A X A | A X B | B X B | B X C | C X C | C X D | D X D | D X E | E X E | E X F | F X F | F X 1 | 1 X 0 | 0 X 2 | 2 X 1 | 1 X 3
/ 2 \ | / 2 \ | / 2 \ | / 2 \ | / 2 \ | / 2 \ | / 2 \ | / 2 \ | / 2 \ | / 2 \ | / 2 \ | / 2 \ | / 2 \ | / 2 \ | / 2 \ | / 2 \ | / 2 \ | / 2 \ | / 2 \ | / 2 \
------+-------+-------+-------+-------+-------+-------+-------+-------+-------+-------+-------+-------+-------+-------+-------+-------+-------+-------+------
\ 2 / | \ 2 / | \ 2 / | \ 2 / | \ 2 / | \ 2 / | \ 2 / | \ 2 / | \ 2 / | \ 2 / | \ 2 / | \ 2 / | \ 2 / | \ 2 / | \ 2 / | \ 2 / | \ 2 / | \ 2 / | \ 2 / | \ 2 /
8 X 8 | 8 X 9 | 9 X 9 | 9 X A | A X A | A X B | B X B | B X C | C X C | C X D | D X D | D X E | E X E | E X F | F X F | F X 1 | 1 X 0 | 0 X 2 | 2 X 1 | 1 X 3
/ 1 \ | / 1 \ | / 1 \ | / 1 \ | / 1 \ | / 1 \ | / 1 \ | / 1 \ | / 1 \ | / 1 \ | / 1 \ | / 1 \ | / 1 \ | / 1 \ | / 1 \ | / 1 \ | / 1 \ | / 1 \ | / 1 \ | / 1 \
------+-------+-------+-------+-------+-------+-------+-------+-------+-------+-------+-------+-------+-------+-------+-------+-------+-------+-------+------
\ 1 / | \ 1 / | \ 1 / | \ 1 / | \ 1 / | \ 1 / | \ 1 / | \ 1 / | \ 1 / | \ 1 / | \ 1 / | \ 1 / | \ 1 / | \ 1 / | \ 1 / | \ 1 / | \ 1 / | \ 1 / | \ 1 / | \ 1 /
8 X 8 | 8 X 9 | 9 X 9 | 9 X A | A X A | A X B | B X B | B X C | C X C | C X D | D X D | D X E | E X E | E X F | F X F | F X 1 | 1 X 0 | 0 X 2 | 2 X 1 | 1 X 3
/ 3 \ | / 3 \ | / 3 \ | / 3 \ | / 3 \ | / 3 \ | / 3 \ | / 3 \ | / 3 \ | / 3 \ | / 3 \ | / 3 \ | / 3 \ | / 3 \ | / 3 \ | / 3 \ | / 3 \ | / 3 \ | / 3 \ | / 3 \

Nice explanation, and that would certainly make for a confusing actual game with so many tiles that are almost-duplicates.

APL (Dyalog Unicode), 112 bytes
⎕CY'dfns'
{⍉¯2↓2↓⍉¯1↓1↓(1,⍨3 7×⍳¨⍵)box⊃⍪/,/⍵↑∘.{(7⍴0 1)\3 3⍴⍺@2 8⊢⍵@4 6,⍨'\//\X'}⍨2,/⎕A[(?5)+16|+\17|⊢∘-\32/⍳8]}

Try it online!
An inline function that takes a single argument, a length-2 vector n m.
The essential idea is taken from Level River St's Ruby solution, i.e. build a De Bruijn sequence of order 2 on a size-16 alphabet.
The rest of the algorithm is just extracting alphabets (with random offset to the alphabet index), arranging into boxes, taking the top left corner of size of the input, and formatting to match the output format.
A bit of work is offloaded to the dfns.box library function, which inserts horizontal and vertical dividers at given indexes using either box-drawing Unicode chars or ASCII.
How it works
⍝ Load library to use the function `box`
⎕CY'dfns'

f←{
  ⍝ Generate the De Bruijn sequence using the observation by Level River St
  idxs←16|+\17|⊢∘-\32/⍳8
                   32/⍳8  ⍝ 1..8, each number copied 32 times
               ⊢∘-\       ⍝ Negate the even indexes (1-based)
            17|           ⍝ Modulo 17; gives 1 16 1 16 ... 2 15 2 15 ... 8 9 8 9
       16|+\              ⍝ Cumul.sum mod 16

  ⍝ Generate tile fragments in one dimension
  axis←2,/⎕A[idxs+?5]
             idxs+?5   ⍝ Add one of 1..5 (random) to all of idxs
          ⎕A[       ]  ⍝ Index into the vector of uppercase letters
       2,/             ⍝ Join adjacent pairs

  ⍝ Generate the matrix of tiles
  mat←⍵↑∘.{(7⍴0 1)\3 3⍴⍺@2 8⊢⍵@4 6,⍨'\//\X'}⍨axis
        ∘.{                                }⍨axis  ⍝ Self outer product over axis
                                  ,⍨'\//\X'  ⍝ '\//\X\//\X'
                   3 3⍴             ⍝ Reshape to 3×3 so the ^ chars form X-frame
                       ⍺@2 8⊢⍵@4 6  ⍝ Place chars of ⍺ vertically, ⍵ horizontally
           (7⍴0 1)\                 ⍝ Insert blanks between columns and outside
      ⍵↑  ⍝ Take n rows and m columns of the entire matrix

  ⍝ Output formatting
  ⍉¯2↓2↓⍉¯1↓1↓(1,⍨3 7×⍳¨⍵)box⊃⍪/,/mat
                             ⊃⍪/,/mat  ⍝ Flatten chars to single matrix
              (          )box  ⍝ Apply box drawing with the options of
                  3 7×⍳¨⍵      ⍝   inserting lines after every 3rd row and 7th col
               1,⍨             ⍝   using ASCII
  ⍉¯2↓2↓⍉¯1↓1↓  ⍝ Fix formatting: drop 1 rows and 2 columns from the outside
}

PowerShell 6, 244 254 bytes
De Bruijn sequence is a good idea. Thanks to Level River St
param($w,$h)for(;$z='A'..'Z'|?{"Z$x"-notmatch-join"$x$_"[-2..-1]}){$x+=''+$z[0]}$v=random 9
1..$h|%{$y=$_+$v
,(($r=1..$w)|%{"\ $($x[$y+$_-1]) /"})+,($r|%{$x[$_-1]+' X '+$x[$_]})+,($r|%{"/ $($x[$y+$_]) \"})|%{$_-join' | '}
,'-----'*$w*($_-ne$h)-join'-+-'}

Try it online!

I've adapted my answer from the topic Generate the shortest De Bruijn for the case {String:'A'..'Z', n:2}.
The script loop by this sequence twice: each tail take two chars by row and by column
The shortest De Bruijn sequence contains 676 chars. That's enough for 255 rows and for 255 columns
The script add random 9 to row numbers to comply with the random requirement
The last line fixed. Output contains extra trailing newline

No-duplicate test generates #### strings instead ASCII tails and is looking for duplicates.

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/


text:
Recursive Steiner Chains
Steiner Chains are a set of N circles where each circle is tangent to 2 other non-intersecting circles as well as the the previous and next circles of the chain, as seen in the below images:

In this challenge, you will write a program/function that draws Steiner chains recursively, that is, circles of a given chain will be the base circles of another iteration of chains:

Challenge
Write a program/function that accepts image dimensions and a list of integers denoting the level of circles in each successive iteration of chains, and output an image with the recursive Steiner chains drawn to it.
Input
Your program/function will accept 2 arguments:

s - width and height of image
ls - list of positive integers denoting the number of circles present in each successive iteration of chains, ordered from the top-most chain to the bottom-most chain

Output
Your program/function will output an image of dimension s x s displaying the recusive Steiner chain.

The top level base circle will be as large as the image with a diameter of s, centered inside the image
To make things easy, the 2 base circles of a Steiner chain will be concentric, that is, the centerpoints of the 2 baseline circles will be the same
Given an outer radius, R, and the number of circles in a chain, N, the formula for the inner radius R' is R' = (R-R*sin(pi/N))/(sin(pi/N)+1)
Circles of the chain as well as the inner base circle will be the outer base circles of the next iteration of chains
While recursing through the chain circles, the order of the next chain should correspond to the next value in ls
While recursing through the inner circle of a chain, the order should be the same as its parents order (example [5,2]):

All chains should end recursion at a depth of the length of ls
The rotation of the chains doesn't matter:

However, the rotations of recursive chains relative to their parents centerpoint should be the same:

All circles should be drawn with an outline or solid fill
Color choice is left to the implementation, save for loopholes (for example, filling everything with the same color)

Example Runs
In the following examples, color is determined by (depth of the recursion)^4.
You can find source here.
chain(600,[5,4,3])

chain(600,[11,1,1,1,1,1,1])

chain(600,[5,6,7,8,9])

Related.

Javascript ES6, 379 bytes
This solution was used to generate the example runs in the question.
f=(s,ls)=>{with(V=document.createElement`canvas`)with(getContext`2d`)with(Math)return(width=height=s,translate(s/=2,s),(S=(o,d=0,n=ls[d],i=(o-o*sin(PI/n))/(sin(PI/n)+1),r=0)=>{fillStyle=`rgba(0,0,0,${pow(d/ls.length,4)})`;beginPath(),arc(0,0,o,-PI,PI),fill();if(d++<ls.length){S(i,d,n);for(;r<n;++r){save();translate(0,(o+i)/2);S((o-i)/2,d);restore();rotate((2*PI)/n);}}})(s),V)}

Ungolfed:
f=(s,ls)=>{                                        // define function that accepts image dimensions and a list of orders
 with(V=document.createElement`canvas`)            // create canvas to draw on, bring its functions into current scope chain
 with(getContext`2d`)                              // bring graphics functions into current scope chain
 with(Math)return(                                 // bring Math functions into current scope chain
  width=height=s,                                  // set width and height of image
  translate(s/=2,s),                               // center the transform on image
   (S=(o,d=0,                                      // define recursive function that accepts outer radius, depth, and optionally order
       n=ls[d],                                    // default chain order to corresponding order in input list
       i=(o-o*sin(PI/n))/(sin(PI/n)+1),            // calculate inner base circle radius
       r=0)=>{                                     // initialize for loop var
    fillStyle=`rgba(0,0,0,${pow(d/ls.length,4)})`; // fill based on depth
    beginPath(),arc(0,0,o,-PI,PI),fill();          // draw circle
    if(d++<ls.length){                             // if within recursion limit
     S(i,d,n);                                     //   recurse on inner circle
     for(;r<n;++r){                                //   loop through all circles of the chain
      save();                                      //   save transform
      translate(0,(o+i)/2);                        //   translate origin to middle of the 2 base circles
      S((o-i)/2,d);                                //   recurse on chain circle
      restore();                                   //   restore transform
      rotate((2*PI)/n);                            //   rotate transform to next circle in chain
   }}})(s),                                        // begin the recursion
 V)}                                               // return the canvas

Note: f returns a canvas.
Example run (assumes there's a <body> to append to):
document.body.appendChild(f(600,[13,7,11,5,3]))

Should dump the following image to the page:

@Dendrobium
I was trying to port @Dendrobium's Javascript answer in Python.
\$\color{red}{\text{But the resolution of my fractal image is terrible.}}\$
from PIL import Image, ImageDraw
import numpy as np
import matplotlib.pyplot as plt

def draw_fractal(s, ls):
    # Create a new image with a white background
    image = Image.new('RGBA', (s, s), color = (0, 0, 0, 0))
    draw = ImageDraw.Draw(image)

    # Begin the recursion
    draw_fractal_recursive(draw, s/2, s/2, s/2, 0, ls, s)

    # Display the image
    plt.imshow(np.array(image))
    plt.show()

def draw_fractal_recursive(draw, x, y, o, depth, ls, s):
    if depth >= len(ls):
        return

    # Chain order to corresponding order in input list
    n = ls[depth]

    # Calculate inner base circle radius
    i = (o-o*np.sin(np.pi/n))/(np.sin(np.pi/n)+1)

    # Fill based on depth
    rgba_color = (0, 0, 0, int(255 * np.power(depth/len(ls), 4)))

    # Draw circle
    draw.ellipse((x-o, y-o, x+o, y+o), fill=rgba_color)

    # Recurse on inner circle
    draw_fractal_recursive(draw, x, y, i, depth+1, ls, s)

    # Loop through all circles of the chain
    for r in range(n):
        # Translate origin to middle of the 2 base circles
        new_x = x + (o+i)/2 * np.cos(2 * np.pi * r / n)
        new_y = y + (o+i)/2 * np.sin(2 * np.pi * r / n)

        # Recurse on chain circle
        draw_fractal_recursive(draw, new_x, new_y, (o-i)/2, depth+1, ls, s)

# Call the function
draw_fractal(600,[13,7,11,5,3])


text:
Normal and visual string reversion
Write some code that acts as a cat program. That is, to input a string and output it as is. But the normal reversion of your code must output the normal reversion of the input string. And the visual reversion of your code must output the visual reversion of the input string.
The normal reversion is the reversed character sequence of a string. The visual reversion is the normal reversion with the characters ()[]{}<> replaced by )(][}{>< respectively.
You could use any codepage that has the characters ()[]{}<> and is published before this challenge to define characters. You must use the same codepage for all your code. Your original code must be valid in this codepage, and applying either of your reversed code to that should yield itself.
This is code-golf, shortest code in bytes wins.
Example
For the string AB(XY), its normal and visual reversions are )YX(BA and (YX)BA respectively.
If your code (in a hypothetical language) is AB(XY), then the code )YX(BA and (YX)BA should output the normal and visual reversions of the input string respectively. And AB(XY) should act as a cat program.

Is it expected that input strings might contain newlines?

@DigitalTrauma Didn't think about that... Your program should support whatever the input routine you use could return (as long as it returns a string). And it should work on the original code itself.

Related http://codegolf.stackexchange.com/q/28190/15599

05AB1E, 16 bytes
Uses the fact that 05AB1E has a constant predefined to "()<>[]{}" and isn't affected the visually reversion.
Code:
,q‡"}{][><)("užR

Explanation:
,                 # Pop and print the input.
 q                # Quit.
  ‡"}{][><)("užR  # This part is ignored.

Try it online!

Reversed:
Ržu"()<>[]{}"‡q,

Explanation:
R                 # Reverse the input.
 žu               # Short for "()<>[]{}".
   "()<>[]{}"     # Push this string.
             ‡    # Transliterate (no-op, since everything is transliterated to itself).
              q   # Quit and implicitly print.
               ,  # This part is ignored.

Try it online!

Visually reversed:
Ržu")(><][}{"‡q,

Explanation:
R                 # Reverse the input.
 žu               # Short for "()<>[]{}".
   ")(><][}{"     # Push this string.
             ‡    # Transliterate (giving the visually reversed string).
              q   # Quit and implicitly print.
               ,  # This part is ignored.

Try it online!
Uses CP-1252 encoding.

CJam, 21 bytes
qe#ere$_"}{][><)("%Wq

Test it here.
Normal reversion:
qW%"()<>[]{}"_$ere#eq

Test it here.
Visual reversion:
qW%")(><][}{"_$ere#eq

Test it here.
Explanation
First, the normal code:
qe#ere$_"}{][><)("%Wq

This is simple: q reads all input, e# comments out the remainder of the program, and the input is printed implicitly at the end.
Now the normal reversion:
q            e# Read all input.
W%           e# Reverse it.
"()<>[]{}"   e# Push this string.
_$           e# Duplicate and sort it. However, the string is already sorted
             e# so we just get two copies of it.
er           e# Transliteration (i.e. character-wise substitution). But since the
             e# source and target string are identical, the reversed input
             e# is left unchanged.
e#eq            Just a comment...

And finally, the visual reversion:
q            e# Read all input.
W%           e# Reverse it.
")(><][}{"   e# Push this string.
_$           e# Duplicate and sort it. This gives us "()<>[]{}", i.e. the
             e# same string with each bracket pair swapped.
er           e# Transliteration (i.e. character-wise substitution). This
             e# time, this toggles all the brackets in the reversed input
             e# completing the visual reversion.
e#eq            Just a comment...

I had exactly this code myself.

Haskell, 124 bytes
Forward:
f=id
--esrever.q pam=2>1|esrever=2<1|f;x=x q;')'='(' q;'('=')' q;']'='[' q;'['=']' q;'>'='<' q;'<'='>' q;'}'='{' q;'{'='}' q

Normal reverse:
q '}'='{';q '{'='}';q '>'='<';q '<'='>';q ']'='[';q '['=']';q ')'='(';q '('=')';q x=x;f|1<2=reverse|1>2=map q.reverse--
di=f

Visual reverse:
q '{'='}';q '}'='{';q '<'='>';q '>'='<';q '['=']';q ']'='[';q '('=')';q ')'='(';q x=x;f|1>2=reverse|1<2=map q.reverse--
di=f

Each version defines a function f which takes and returns a string. In forward mode f is the identity function id, the rest of the code is a comment. In normal reverse mode the guard 1<2 in f is True, so reverse is applied. In visual reverse mode, the < is switched to > and the guard is False. The second guard is just the other way around and Truein visual mode, so additionally q is applied which switches "()<>{}[]".
f|1<2=reverse|1>2=map q.reverse      -- normal reverse mode
f|1>2=reverse|1<2=map q.reverse      -- visual reverse mode

Besides <and > in the guards, my code doesn't use any of the brackets, so they can't be messed up.

Bash + common linux utilities, 51

2 bytes saved thanks to @jimmy23013
2 bytes saved thanks to @AdamKatz

#'><}{][)(' `P5BD706D5AC79E196iFe- cd` rt|ver|
\cat

Normal reversion:
tac\
|rev|tr `dc -eFi691E97CA5D607DB5P` '()[]{}<>'#

Visual reversion:
tac\
|rev|tr `dc -eFi691E97CA5D607DB5P` ')(][}{><'#

The main trick here is that the string ()[]{}<> is encoded as 691E97CA5D607DB5 (base 15).  The resulting dc command will yield this same result after either kind of reversion.  However the '()[]{}<>' string literal is sensitive to the reversal type.
tac is required to reverse order of input lines and rev is required to reverse the characters of each line.  Any ASCII input should be acceptable.

MATL, 26 24 22 16 bytes
Forward
DPEXSt'><}{][)('

Try it Online!
Explanation:
                % Implicitly grab the input as a string
D               % Pop the top of the stack and display it
P               % Tries to flip the top element on the stack but errors out
                % because the stack is empty. Program terminates.
EXSt'><}{][)('  % Not executed

Normal reversion:
'()[]{}<>'tSXEPD

Try it Online!
Explanation:
            % Implicitly grab input as a string
'()[]{}<>'  % String literal (search string)
tS          % Duplicate and sort to create the replacement string: '()[]{}<>'
XE          % Replace all entries in the input using the search and replacement strings.
            % Corresponding characters in the strings are used for the replacement.
            % Effectively a no-op
P           % Flip the string
D           % Explicitly display result

Visual reversion:
')(][}{><'tSXEPD

Try it Online!
Explanation:
            % Implicitly grab the input as a string
')(][}{><'  % String literal (search string)
tS          % Duplicate and sort to create the replacement string: '()[]{}<>'
XE          % Replace all entries in the input using the search and replacement strings.
            % Corresponding characters in the strings are used for the replacement.
P           % Flip the result
D           % Explicitly display the result

The visual reversion is the normal reversion with the characters ()[]{}<> replaced by )(][}{>< respectively.

@ΈρικΚωνσταντόπουλος Updated.

GolfScript, 32 28 bytes
#%{=1-[=-\7?@.`{[(<>)]}.}%1-

Try it online!
Normal reversion:
-1%}.}])><([{`.@?7\-=[-1={%#

Try it online!
Visual reversion:
-1%{.{[(<>)]}`.@?7\-=]-1=}%#

Try it online!
The fact that an unmatched } terminates the program in GolfScript, made this fairly simple. However, I'm pretty sure that my code for swapping the brackets isn't optimal yet.

Python 2.7, 208 bytes
Forward
import sys#
print''.join(sys.stdin)#
#0:tpecxe
#"]1-::[)nidts.sys(nioj.'' tnirp"cexe:yrt
#0:tpecxe
#"(('<>{}[]()','><}{][)(')snartekam.s)etalsnart.[1-::](nidts.sys)nioj.'' tnirp"cexe:yrt
#s sa gnirts,sys tropmi

Normal reversion
import sys,string as s#
try:exec"print''.join)sys.stdin(]::-1[.translate)s.maketrans)'()[]{}<>',')(][}{><'(("#
except:0#
try:exec"print''.join(sys.stdin)[::-1]"#
except:0#
#)nidts.sys(nioj.''tnirp
#sys tropmi

https://eval.in/574639
Visual reversion
import sys,string as s#
try:exec"print''.join(sys.stdin)[::-1].translate(s.maketrans(')(][}{><','()[]{}<>'))"#
except:0#
try:exec"print''.join)sys.stdin(]::-1["#
except:0#
#(nidts.sys)nioj.''tnirp
#sys tropmi

https://eval.in/574638
All directions read from stdin until EOF.
Nothing super clever here. Trailing comments to only execute the forward vs the backward code, then an exec statement in a try block to catch syntax errors for the two different reversions.


text:
Find the last three words of each paragraph if they are shorter than 20 characters in total
Based on my SO question, but more specifically:
Find a RegEx such that, given a text where paragraphs end with an empty line (or $ at the very end), match the up to twenty last characters of a paragraph excluding the \r or $ but no more than three complete "words" including the "separators" in between and the punctuation following it. The following constraints apply:

"words" also include abbreviations and the like (and thus punctuation), i.e. "i.e." and "non-trivial" count as one word each
whitespaces are "separators"
isolated dashes do not count as "words" but as "separators"
"separators" before the first word must not be included
trailing punctuation counts to that limit, but not the leading one nor the linebreaks and $ that must not be in the matching group
whether trailing punctuation is included in the match or not is up to you

Some examples:

The early bird catches the worm. Two words.
But only if they got up - in time.
Here we have a supercalifragilisticexpialidocious etc. sentence.
Short words.
Try accessing the .html now, please.
Vielen Dank und viele Grüße.
Did any-one try this?

Score is given in bytesteps: bytes multiplied by amount of steps according to https://regex101.com, but there are three penalties:

if the upper limit of words cannot trivially+ be modified: +10%
if the upper limit of character count cannot trivially+ be modified: +10%
failure to handle unicode used in actual words: add the percentage of world population speaking the language according to Wikipedia the failing word stems from. Example: Failing to match the German word "Grüße" as a word => +1.39%. Whether you consider a language's letters as single characters or count the bytes to utf8-encode them is up to you. The penalty does not have to be applied before someone actually provides a counter-example, so feel free to demote your competitors ;)

Since this is my first challenge, please suggest any clarifications. I assume regular-expression means there are no "loopholes" to exclude.

+ With trivially modified I mean expressions such as {0,2} and {21} are valid but repeating something three times (which would have to be re-repeated to increase the amount words) is not.

Bonuses and penalties are generally disliked in challenges. And, while it makes sense to restrict this to regular expressions, why not remove the tag and let other languages compete as well?

@VTCAKAVSMoACE I assume because it's not just scored by bytes but also by the number of steps executed by the regex engine, which doesn't make sense for arbitrary languages.

Could you add test cases where a) there's leading punctuation, b) there's a hyphen that isn't surrounded by whitespace c) a paragraph that consists only of one of two words taking up much less than 20 characters?

Also the penalties aren't entirely clear. Of course the upper limit of words and characters can always be modified, it's just a question of how many places need to be changed. Do you mean 3 and 20 should appear as numbers in a single place which can be changed?

Will \s\s+ ever match the paragraph?

@MartinBüttner Thanks for the feedback, I hope my examples and clarifications help. I don't require 3 and 20 to exactly occur, things like {0,2} and {21} are ok as well. I just wanted to penalize explicit pattern repetitions (e.g. \w+\s\w+\s\w+ instead of a more generalize-able (?:\w+\s){0,2}\w+ even though that is longer)

Can you clarify what you mean by matching group, i.e. can you specify a particular capturing group as the result?

@Neil I'd prefer having only one capturing group which would then be the result

@KennyLau Markdown's manual line-break (two spaces at the end of the line and no empty line) matches that but I wouldn't consider it a paragraph.

Is there any manual repetition that is not able to be converted into a thing like {0,2}?

Can I match the leading whitespace?

You should clarify more. I thought the spaces do not count towards the character limit...

@KennyLau 1) no there isn't but one shouldn't use repetition even if it's shorter 2) matching the leading whitespace is not valid 3) the spaces in between also count towards the character limit - the regex would become pretty complex otherwise I guess?

Please avoid unclear terms such as "desired".

@KennyLau Sorry, you're right. Matching it is disallowed.

I am still not seeing the word "regex" in your question anywhere.

@KennyLau fixed. I also forgot an example with hyphen...

37 bytes * 1403 steps = 51911 bytesteps
34 bytes * 1036 steps = 35224 bytesteps
37 bytes * 666 steps = 24642 bytesteps
(?<!\S)(?!.{21})\S+(( | - )\S+){0,2}$

Verify it here!

I think the challenge is explicitly asking for just a regex, not a solution in any other programming language. So a) you can omit the `!``, but b) you'll have to make sure in works in PCRE so that it can be scored on regex101.

I don't think you need the 1 in {1,3}, neither in {1,20}

@Bálint He does, otherwise it matches exactly 3 words or 20 characters. (And if you mean {,20} that only works in Ruby and some other flavours, but definitely not .NET.)

@MartinBüttner is right I'm afraid, unless you can provide means to calculate an equivalent to regex101's step counting in order to obtain a score in bytesteps. Sorry for the confusion - maybe I should ask a second question that is pure code-golf without the regex-bytesteps, but it would be otherwise identical, so I don't know if that is acceptable

@MartinBüttner nope, I meant {20}

@Bálint Yeah that won't work for less then 3 words and 20 characters then. Also Kenny, I don't think your use of \b works when the match would start with something other than a word character.

@TobiasKienzler It's extremely unclear. The word regex only appears once throughout your whole question (and it even is a part of the address a website), and it is not even tagged as [tag:regex]

@KennyLau Sorry about the confusion - unfortunately there is only a tag [tag:regular-expression], I also wanted to use [tag:regex]...

Oh, I overlooked. Anyhow, the word regex still isn't explicitly mentioned in the challenge.

Sorry, I forgot to add a hyphen-example. That increases the steps (my bad) slightly to 1403

Instead of (?=.{1,20}$) you can use (?!.{21}), right? The $ is checked for again at the end anyway. (?<!\S)(?!.{21})(\S+ ?(- )?){1,3}$ gives you 34*1036 = 35224 bytesteps

You can get down to 578 steps by replacing (?<!\S with (?<=\s

@TobiasKienzler Doesn't work for the beginning?

You're right, I didn't consider that, thanks for pointing it out


text:
Will the beam hit?
A laser shoots a straight beam in one of the four orthogonal directions, indicated by <>^v. Determine whether it will hit the target O on a rectangular grid.
Each of these will hit (True):
.....
...O.
.....
...^.
.....

>O.
...

v....
O....

...........
...........
O.........<
...........

These will miss (False):
......
......
.^..O.

......
.....>
O.....
......
......

.O.
...
.v.

.....<.
..O....

Input: A rectangular grid of ., sized at least 2x2, with exactly one target O and one laser that's one of <>^v. The lines can be a list of strings, a 2D array or nested list of characters, or a single newline-separated string with an optional trailing newline.
Output: A consistent truthy value if the laser beam hits the target, and a consistent falsy value if it misses.
I'll consider submissions that don't use regular expressions (or built-in pattern-based string matching) as a separate category. If you put (no regex) after the language name, your answer will appear separately in the leaderboard.

var QUESTION_ID=80196,OVERRIDE_USER=20260;function answersUrl(e){return"https://api.stackexchange.com/2.2/questions/80196/answers?page="+e+"&pagesize=100&order=desc&sort=creation&site=codegolf&filter="+ANSWER_FILTER}function commentUrl(e,s){return"https://api.stackexchange.com/2.2/answers/"+s.join(";")+"/comments?page="+e+"&pagesize=100&order=desc&sort=creation&site=codegolf&filter="+COMMENT_FILTER}function getAnswers(){jQuery.ajax({url:answersUrl(answer_page++),method:"get",dataType:"jsonp",crossDomain:!0,success:function(e){answers.push.apply(answers,e.items),answers_hash=[],answer_ids=[],e.items.forEach(function(e){e.comments=[];var s=+e.share_link.match(/\d+/);answer_ids.push(s),answers_hash[s]=e}),e.has_more||(more_answers=!1),comment_page=1,getComments()}})}function getComments(){jQuery.ajax({url:commentUrl(comment_page++,answer_ids),method:"get",dataType:"jsonp",crossDomain:!0,success:function(e){e.items.forEach(function(e){e.owner.user_id===OVERRIDE_USER&&answers_hash[e.post_id].comments.push(e)}),e.has_more?getComments():more_answers?getAnswers():process()}})}function getAuthorName(e){return e.owner.display_name}function process(){var e=[];answers.forEach(function(s){var r=s.body;s.comments.forEach(function(e){OVERRIDE_REG.test(e.body)&&(r="
"+e.body.replace(OVERRIDE_REG,"")+"
")});var a=r.match(SCORE_REG);a&&e.push({user:getAuthorName(s),size:+a[2],language:a[1],link:s.share_link})}),e.sort(function(e,s){var r=e.size,a=s.size;return r-a});var s={},r=1,a=null,n=1;e.forEach(function(e){e.size!=a&&(n=r),a=e.size,++r;var t=jQuery("#answer-template").html();t=t.replace("{{PLACE}}",n+".").replace("{{NAME}}",e.user).replace("{{LANGUAGE}}",e.language).replace("{{SIZE}}",e.size).replace("{{LINK}}",e.link),t=jQuery(t),jQuery("#answers").append(t);var o=e.language;/s.lang?1:e.lang<s.lang?-1:0});for(var c=0;c<t.length;++c){var i=jQuery("#language-template").html(),o=t[c];i=i.replace("{{LANGUAGE}}",o.lang).replace("{{NAME}}",o.user).replace("{{SIZE}}",o.size).replace("{{LINK}}",o.link),i=jQuery(i),jQuery("#languages").append(i)}}var ANSWER_FILTER="!t)IWYnsLAZle2tQ3KqrVveCRJfxcRLe",COMMENT_FILTER="!)Q2B_A2kjfAiU78X(md6BoYk",answers=[],answers_hash,answer_ids,answer_page=1,more_answers=!0,comment_page;getAnswers();var SCORE_REG=/<h\d>\s*([^\n,]*[^\s,]),.*?(\d+)(?=[^\n\d<>]*(?:<(?:s>[^\n<>]*<\/s>|[^\n<>]+>)[^\n\d<>]*)*<\/h\d>)/,OVERRIDE_REG=/^Override\s*header:\s*/i;
body{text-align:left!important}#answer-list,#language-list{padding:10px;width:290px;float:left}table thead{font-weight:700}table td{padding:5px}
 <link rel="stylesheet" type="text/css" href="//cdn.sstatic.net/codegolf/all.css?v=83c949450c8b">

Leaderboard

	Author	Language	Size

Winners by Language

Language	User	Score

{{PLACE}}	{{NAME}}	{{LANGUAGE}}	{{SIZE}}	Link

{{LANGUAGE}}	{{NAME}}	{{SIZE}}	Link

Related

I don't know much about Fission, but I'll bet someone could write a program to turn the input into Fission code and run it.

Actually, am I allowed to take the input fully surrounded by semicolons (;) and with the ^V<> replaced by UDLR?

Can input be a 2d array of characters?

@Mystagogue No, you'd have do any such processing yourself.

@Doorknob Sure.

I was hoping you would include mirrors with / and \ . Maybe for another question...

@vsz that's what I was thinking! xnor should post this modification too.

@vsz There's already this.

Still waiting for Mathematica built-in

@Mego ... which makes this challenge a lot simpler and allows for very different approaches.

Our policy on what constitutes a duplicate challenge states that, if solutions can be copied with no/minimal modification and still be valid and competitive, then the challenge is a duplicate. The (current) shortest solution on the older challenge is 260 bytes, which is shorter than 5 of the solutions here (though I don't know if we want to include the longer solution in the same language). That solution is clearly competitive, thus dupe.

@Mego I disagree; by that logic, the plain hello world challenge is a duplicate of dozens of other challenges at the same time. Anyway, thanks for notifying me about the power I now have to close/reopen code golf challenges, I wasn't aware of that.

@aditsu The Hello World challenge would be a dupe, but we as a community have chosen to allow it because of its significance to programming.

@Mego another thing is: any solution to the older challenge can be made significantly shorter (in the same language) by removing the parts that deal with mirrors, and more importantly, can be made significantly shorter again by using a different approach. I don't count those as "minimal modifications".

@aditsu That's a difference of opinions; I would consider simply removing any number of characters/bytes/tokens/statements from a solution to be a trivial modification.

@Mego Although this question is a special case of the other one, I don't believe it to be a dupe because the answers use totally different approaches. On that question, they all compute the path the beam takes. Portals can move the path from anywhere to anywhere which doesn't seem to a allow a shortcut, and reflectors are tricky to handle. Answers here instead mostly check or match some property of the input string. Sure, you can copy a path-tracing answer from the other challenge and remove the extra bits, but this method is overkill and gives a needlessly long solution.

There's a clear consensus that we shouldn't have an easy version of a different challenge.

Snails, 19 bytes
\>|\<l|\^u|\vd).,\O

The spec for this one can be implemented as literally as possible, no thinking required.

Can you add an explanation of how this works?

@QPaysTaxes Until feersum gets around to it, hopefully this will help: Snails is a 2D pattern matching language. udlr set the direction of the snail to up/down/left/right. | works like it does in regular regex, and ) doesn't need a matching open parenthesis. So the code pretty directly translates to "Find one of v<>^ and set the direction appropriately, then try to find an O in that direction."

Yeah, what Eggman said. The only other thing is that , is like the * of regex.

Retina, 56 52 42 38 31 30 bytes
Saved 1 byte thanks to @MartinBüttner
O.*<|>.*O|[vO](.*¶)[^O]*[O^]\1

Abuses properties of rectangles. Requires input to have a trailing newline.
Try it online
Explanation
This works in three parts:

Matching >
Matching <
Matching ^ and v this is because the logic for ^ and v are really the same, just the characters.

Validating <
This is simple:
O.*<

This matches an O, optionally followed by non-newline chars, then a <
Validating >
This is much the same as the previous way except the other way around. First a > is matched, then the O
Validating ^ and v
This was difficult to golf and took adverting of the input always being valid. First, we match whether it's v or an O:
[vO]

If it's an ^, the first character that's encountered should be a O. So, this matches the first character to match. Next we count the amount of .s following it up to the newline:
(.*\n)

Next, this can go into two parts, I'll cover the first:
So first, we match until the following O, using:
[^O]*O

This optionally matches all non-O characters until an O is encountered, if this is successful, then it continues... if not, then the following happens...
Now, it attempts to find the ^ using:
[^^]*\^

^ is a special character in regex so it needs to be escaped. [^^] matches all characters except ^, this works the same as the above, if this succeeds, then the following happens...
So now, one of the above has matched succesfully, the \1 checks and sees if the capture group from before (.*\n), this capture group stored the amount of .s there were after either the v or O from before, so now \1 just checks if the amount of dots in the same.

You can save a byte by using ¶ instead of \n (Retina can handle source code in ISO 8859-1.)

@MartinBüttner thought ¶ was only \n in replacements, thanks for the tip!

no it works anywhere in the source code. After splitting the file into lines, the first thing Retina does is replace the ¶ everywhere, before doing any further parsing.

Java (no regex), 413 412 246 242 212 211 209 198 bytes
Competing in golf challenges using java has less sense than take a part in Formula 1 race on bicycle, but I'm not always doing thinks which makes any sense.
Here is my extremely long java solution
Golfed version
boolean l(char[][]w){int[]t={},l={};for(int y=0;y<w.length;y++)for(int x=0;x<w[0].length;x++){if(w[y][x]=='O')t=new int[]{x,y};if(w[y][x]=='<')l=new int[]{x,y,1};if(w[y][x]=='>')l=new int[]{x,y,2};if(w[y][x]=='v')l=new int[]{x,y,3};if(w[y][x]=='^')l=new int[]{x,y,4};};return(l[2]==1&&l[1]==t[1]&&l[0]>t[0])||(l[2]==2&&l[1]==t[1]&&l[0]<t[0])||(l[2]==3&&l[0]==t[0]&&l[1]<t[1])||(l[2]==4&&l[0]==t[0]&&l[1]>t[1]);}

and ungolfed
boolean l(char[][] w) {
    int[] t = {}, l = {};
    for (int y = 0; y < w.length; y++)
        for (int x = 0; x < w[0].length; x++) {
            if (w[y][x] == 'O')
                t = new int[] { x, y };
            if (w[y][x] == '<')
                l = new int[] { x, y, 1 };
            if (w[y][x] == '>')
                l = new int[] { x, y, 2 };
            if (w[y][x] == 'v')
                l = new int[] { x, y, 3 };
            if (w[y][x] == '^')
                l = new int[] { x, y, 4 };
        }
    ;
    return (l[2] == 1 && l[1] == t[1] && l[0] > t[0])
            || (l[2] == 2 && l[1] == t[1] && l[0] < t[0])
            || (l[2] == 3 && l[0] == t[0] && l[1] < t[1])
            || (l[2] == 4 && l[0] == t[0] && l[1] > t[1]);
}

Seems like my entire concept was wrong, here is my shorter solution
boolean z(char[][]w){int x=0,y=0,i=0,a=w.length,b=w[0].length;for(;w[y][x]!=79;)if(++y==a){y=0;x++;}for(;i<(a<b?b:a);)if(i<b&w[y][i]==(i<x?62:60)|i<a&w[i][x]==(i++<y?'v':94))return 1<2;return 1>2;}

and ungolfed version
oolean z(char[][] w) {
        int x = 0, y = 0, i = 0, a = w.length, b = w[0].length;
        for (; w[y][x] != 79;)
            if (++y == a) {
                y = 0;
                x++;
            }
        for (; i < (a < b ? b : a);)
            if (i < b & w[y][i] == (i < x ? 62 : 60) | i < a
                    & w[i][x] == (i++ < y ? 'v' : 94))
                return 1 < 2;
        return 1 > 2;
    }

EDIT
I rewrote code for looking for 'O', now it contains single loop is much shorter, and I also used @Frozn suggestion to replace some of characters with their ascii values.
In result,another 30 bytes bites the dust.
Another suggestion from @Frozn, and we are couple bytes closer to Python solution
Another rewrite drop one loop, and combine two if statements

+1 You can remove the space between return and ( to save a byte, though. The space isn't necessary when your return value is inside parenthesis (or quotes for Strings). Source from the Java code-golfing tips.

@KevinCruijssen not saving much, but thanks:)

Every little bit (or should I say byte) helps I guess. ;) Besides, I don't think Java will ever win a code-golf challenge anyway. I still like doing code-golf challenges in Java though, especially since I'm currently working with Java at work.

You can replace the chars by their ASCII value: 'O' = 79, '>' = 62, '<' = 60, '^' = 94. For 'v' it's 118 but that doesn't shorten the code.

@Frozn as Kevin said, in every byte counts.

By putting the the first i=0 to the top of the function you can save another character. Also if you make the whole function a Java 8 lambda you can save even more. And of course every byte/character counts! It's Java ;) Edit: You can also make int a=w.length to save the duplicate long version.

@Frozn  thanks again

MATL (no regex), 26 25 24 22 bytes
'>v<^'XJymfX!tZpYswJm)

Try it Online!
Modified version for all test cases
Explanation
        % Implicitly grab input
'>v<^'  % String literal indicating the direction chars
XJ      % Store in the J clipboard
y       % Copy the input from the bottom of the stack
m       % Check to see which of the direction chars is in the input. The
        % result is a 1 x 4 logical array with a 1 for the found direction char
f       % Get the 1-based index into '>v<^' of this character
X!      % Rotate the input board 90 degrees N times where N is the index. This
        % Way we rotate the board so that, regardless of the direction char,
        % the direction char should always be BELOW the target in the same column
t       % Duplicate
Zp      % Determine if any elements are prime ('O' is the only prime)
Ys      % Compute the cumulative sum of each column
w       % Flip the top two stack elements
J       % Grab '>v<^' from clipboard J
m       % Create a logical matrix the size of the input where it is 1 where
        % the direction char is and 0 otherwise
)       % Use this to index into the output of the cumulative sum. If the
        % direction char is below 'O' in a column, this will yield a 1 and 0 otherwise
        % Implicitly display the result

@LuisMendo Now to figure out how to get rid of J

I don't know MATL, so this may be a silly question, but why is 0 prime?

@Neil It's letter 'O',  not number 0. ASCII code for letter 'O' is 79

Ugh, I guess I would have still been fooled if you'd been looking for odd numbers instead.

CJam (no regex), 25
Earlier versions were wrong, this will have to do for now:
q~_z]{'.-HbI%}f%[HF].&~+,

Try it online
Explanation:
q~         read and evaluate the input (given as an array of strings)
_z         copy and transpose
]          put the original grid and transposed grid in an array
{…}f%      map the block to each grid (applying it to each string in each grid)
  '.-      remove all dots (obtaining a string of 0 to 2 chars)
  Hb       convert to base H=17, e.g. ">O" -> 62*17+79=1133
  I%       calculate modulo I=18
[HF]       make an array [17 15]
.&         set-intersect the first array (mapped grid) with 17 and 2nd one with 15
~+         dump and concatenate the results
,          get the array length

I tried a few mathematical formulas for distinguishing between "good" and "bad" strings, and for each type of formula I tried plugging in various numbers. I ended up with the HbI% above.
"good" strings for the original grid are ">O" and "O<" and they give the result 17
"good" strings for the transposed grid are "vO" and "O^" and they give the result 15
"bad" strings for both grids are: ">", "<", "^", "v", "O", "", "O>", "Ov", "<O", "^O" and they give the results 8, 6, 4, 10, 7, 0, 1, 3, 1, 3

Python 3 (no regex), 184 bytes.
Hooray for eval hacking!
def f(a,o=0,d={},q=''):
 for r in a:
  i=0
  for c in r:d[c]=o,i;i+=1;q=(c,q)[c in'O.']
  o+=1
 z,y=d['O'];e,j=d[q];return eval("z%se and y%sj"%(('><'[q<'v'],'=='),('==',q))[q in'><'])

TSQL (sqlserver 2012) (no regex), 358 bytes
DECLARE @ varchar(1000)=
'......'+ CHAR(13)+CHAR(10)+
'......'+ CHAR(13)+CHAR(10)+
'...0..'+ CHAR(13)+CHAR(10)+
'...^..'+ CHAR(13)+CHAR(10)
;

WITH C as(SELECT
number n,SUBSTRING(@,number,1)a,1+min(IIF(SUBSTRING(@,number,1)=char(13),number,99))over()m
FROM master..spt_values
WHERE'P'=type and
SUBSTRING(@,number,1)in('>','<','^','v','0',char(13)))SELECT
IIF(c.n%c.m=d.n%c.m and c.a+d.a in('0^','v0')or
c.n/c.m=d.n/c.m and c.a+d.a in('>0','0<'),1,0)FROM c,c d
WHERE c.n<d.n and char(13)not in(c.a,d.a)

Had to use funky linechange in the declaration to force the online version to execute it(assigning values to input variables doesn't affect the length calculation anyway)
Try it online!

Pyth, 43 bytes
KxJ"^<v>"h@Js.z}\Ohc_W>K1hf}@JKTCW!%K2.z@JK

Live demo.

Ruby, 71 55 54 bytes
Regex solution, which means that it's probably going to be easily beaten by Retina or Perl.
Returns an index number (truthy) if there is a match.
Now with a similar trick to @Downgoat Retina answer, matching for down and up beams at the same time.
->m{m=~/>\.*O|O\.*<|(?=[vO])(.{#{??+m=~/\n/}})+[O^]/m}

JavaScript (ES6), 78 bytes
s=>s.match(`>.*O|O.*<|(?=v)([^]{${l=s.search`\n`+1}})+O|(?=O)([^]{${l}})+\\^`)

Regexp of course. Turned out to be similar in principle to the Ruby answer.

JavaScript (ES6) (no regex), 126 bytes
s=>([n,o,l,r,u,d]=[..."\nO<>^"].map(c=>1+s.indexOf(c)),l>o&l-o<n&l%n>o%n||r&&r<o&o-r<n&r%n<o%n||u>o&u%n==o%n||d&&d<o&d%n==o%n)

Where \n represents the literal newline character.

Julia (no regex), 98
a->(c=rotr90(a,findlast("i1Q/",sum(a-46)));
    f(n)=find(any(c.!='.',n));b=c[f(2),f(1)];
    (b'*b)[1]==97)

Function operating on an array of chars, normalizing by rotation, removing rows and columns containing only dots by range indexing and finally checking for location of 'O' taking into account if the remainder b is a column or row vector using matrix multiplication.
Try it online

Clojure (no regex), 293 bytes
(defn z[f](let[v(sort(keep-indexed(fn[i v](if(some #{v}[\v\>\<\^\O])[(if(= v\O)\& v)i]))f))l(+(.indexOf f"\n")1)d((nth v 1)0)q((nth v 1)1)p((nth v 0)1)r(=(quot p l)(quot q l))i(> q p)](cond(= d\^)(and i(=(mod(- q p)l)0))(= d\v)(and(not i)(=(mod(- p q)l)0))(= d\>)(and(not i)r):else(and i r))))

Doesn't feel great. Straightforward solution, finding the index of corresponding characters and calculating if they're on the same line.
You can try it here https://ideone.com/m4f2ra

Python (no regex), 105 bytes
def f(s):t=s.strip('.\n');return not['\n'in t,len(t)%(s.find('\n')+1)!=1,1]['>O<vO^'.find(t[0]+t[-1])//3]

returns True or False
First, strips '.' and '\n' from the ends so that the characters of interest, '0<>v^', are the first and last characters.
'>O<vO^'.find(t[0]+t[-1])//3 - checks if the characters are a potentially valid arrangement. Evaluates to 0 for '>O' or 'O<', to 1 for 'vO' or 'O^', and to -1 for anything else.
'\n'in t - checks if the characters are in different rows,
len(t)%(s.find('\n')+1)!=1 - checks if they are in different columns, and
1 - is the default
The not inverts the result selected from the list, so the return expression is equivalent to:
t[0]+t[-1] in '>0<' and '\n' not in t or t[0]+t[-1] in 'vO^' and len(t)%(s.find('\n')+1)==1

Python 2 (no regex), 268 bytes
import numpy
def q(i):
 s=numpy.asmatrix(i)
 for n in s:
  n=n.tolist()[0]
  try:
   a=n.index("0")
   if n.index(">")<a or n.index("<")>a:return 1
  except:0
 for n in range(len(i)):
  c=[x[0] for x in s[:,n].tolist()]
  try:
   a=c.index("0")
   if c.index("v")a:return 1
  except:0
 return 0

Truthy and Falsy values returned by the function are 1 and 0, respectively.
I haven't had a chance to golf yet. Honestly, I'm not too hopeful for this one...
Any suggestions would be greatly appreciated!

C# (No Regex), 282 bytes
bool F(char[,]b){int k=0,l=1,m=1,n=0,o=0;for(int x=0;x<b.GetLength(0);x++)for(int y=0;y<b.GetLength(1);y++){char i=b[x,y];if(i=='O'){k=x;l=y;}if(new[]{'<','>','^','v'}.Contains(i)){m=x;n=y;o=i;}}return(o==60&&k==m&&l<n)||(o==62&&k==m&&l>n)||(o==94&&l==n&&k<m)||(o==118&&l==n&&k>m);}

Works like the java version but transpiled and reduced
Expanded (Explanation included):
bool F(char[,] b)
{
    // declare variables for goal x, goal y, laser x, laser y, and laser direction respectively (laser direction is char code for directions)
    int k = 0, l = 0, m = 0, n = 0, o = 0;
    // go through each cell
    for (int x = 0; x < b.GetLength(0); x++)
    {
        for (int y = 0; y < b.GetLength(1); y++)
        {
            // get cell contents
            char i = b[x, y];
            // set goal position if goal
            if (i == 'O')
            {
                k = x;
                l = y;
            }
            // set laser position and direction if laser
            if (new[]{ '<', '>', '^', 'v' }.Contains(i))
            {
                m = x;
                n = y;
                o = i;
            }
        }
    }
    // check everything is on the same line and in right direction
    return (o == 60 && k == m && l < n) ||
           (o == 62 && k == m && l > n) ||
           (o == 94 && l == n && k < m) ||
           (o == 118 && l == n && k > m);
}

C (ANSI) (No regex), 237 bytes
#define l b[1][i]
main(i,b,c,d,x,y,z,p)char **b;{for(y=z=i=0,x=1;z<2&&(l==10?x=0,++y:1);i++,x++)if(l>46){if(l!=79)p=l;if(!z++)c=x,d=y;}i--;x--;z=(c==x)*((p=='v')*(l==79)+(p==94)*(l==p))+(d==y)*((p==60)*(l==p)+(p==62)*(l==79));return z;}

Expanded:
#define l b[1][i]
main(i,b,c,d,x,y,z,p)char **b;{
    for(y=z=i=0,x=1;z<2&&(l==10?x=0,++y:1);i++,x++)
        if(l>46){if(l!=79)p=l;if(!z++)c=x,d=y;}
    i--;x--;
    z=(c==x)*((p=='v')*(l==79)+(p==94)*(l==p))+(d==y)*((p==60)*(l==p)+(p==62)*(l==79));
    printf("%i\n",z);
    return z;
}

I think I took a decently different approach here compared to the Java or C# implementations. I got coordinates of the 'O' and arrow ((c,d) and (x,y)) and then compared them to see if the arrow was pointing in the correct direction.
Returns 0 if false and 1 if true

Grime v0.1, 31 bytes
n`\>.*a|a.*\<|\v/./*/a|a/./*/\^

Not a very interesting solution. Prints 1 for truthy instances, and 0 for falsy ones. Try it online!
Explanation
We simply search the input rectangle for a minimal-size (n×1 or 1×n) pattern that contains the laser and target in the correct order.
The n` flag makes the interpreter print the number of matches, of which there will always be at most one.
The rest of the line consists of four patterns separated by |-characters, which means a logical OR: a rectangle is matched if it matches one of the patterns.
The patterns work as follows:
\>.*a    Literal ">", horizontal row of any chars, one alphabetic char
a.*\<    One alphabetic char, horizontal row of any chars, literal "<"
\v/./*/a Literal "v", on top of vertical column of any chars, on top of one alphabetic char
a/./*/\^ One alphabetic char, on top of vertical column of any chars, on top of literal "^"


text:
Let's play ASCII mini-golf
Let's play code golf... by playing golf.
Input
Your input will be a string consisting of #'s, an o, an @, and .'s. For example:
......@..
.....##..
.........
......o..

. - playable golf course (all shots must end on one of these)
# - a barrier (shots cannot go through this)
o - the starting position of your golf ball
@ - the hole
How to Play ASCII Golf
You start at the o. Here is a valid shot from point A to point B:
1) This shot is straight line that can be drawn between A and B (no curved shots).
A....
....B

2) The line AB may not intersect with a # (barrier), e.g.:
A.#.B

It may, however, be tangent to a barrier:
A#
.B

3) (For clarity) You may not bounce shots off barriers or the edge of the golf course.
Output
Print to stdout (or an acceptable equivalent) the minimum number of shots to get the ball into the hole @. If it is not possible, print -1.
Examples
o....@

=> 1
o.#.@

=> -1
o..#
..#@

=> 2 (you can pass through the vertices of a #, but not the edges)
o#...#
.#.#.#
...#.@

=> 4

Can’t your “6” example be done in 4 shots (south 1, southeast 1, northeast 2, southeast 2)?

In the worst case you would need to write/golf a pathfinder algorithm like A* or something similar. Which may be quite difficult/challenging for some languages.

@AndersKaseorg Good point, fixed.

What would ..@ \no#. mean?

Can you do this in 1 shot? o### / #..# / ###@ (3 rows)

i think that op must define which particular cases make a ball rebouncing off an egde.

@AndersKaseorg why can it not be 3 ? south 2, n-e 3, etc ..

@aditsu No, because the line would intersect the edge of a #.

@Agawa001 The question is clear: “You may not bounce shots off barriers or the edge of the golf course.” And no, there’s no 3 shot solution.

What about this: o.## / ##.@ ? 1 shot?

@aditsu. Yes, because the line from o to @ only intersects the vertices of the #'s

What? On hold? I'm pretty clear about the challenge now, but it took a couple of comments to make sure. @AMACB you should probably explain the exact trajectory of the ball and shape of the barriers more clearly. If not, maybe I can edit the question later.

I don't have time right now, but I will try to get to it soon.

Python 2, 469
Pretty long, but it's a start:
R=range
def l(c,x,y,z,t):
 f=abs(z-x);g=1-2*(z<x);p=abs(t-y);q=1-2*(t<y);v=r=0
 for i in R(f):
  w=f+(2*i+1)*p
  for j in R(v,(w-1)/2/f+1):r|='.'>c[x+g*i][y+q*j]
  v=w/2/f
 for j in R(v,p+1):r|='.'>c[z][y+q*j]
 return r
def f(c):
 a="".join(c);n=len(c[0]);b=len(a);d=[[9**9*l(c,i/n,i%n,j/n,j%n)+1for i in R(b)]for j in R(b)]
 for k in R(b):
  for i in R(b):
   for j in R(b):
    t=d[i][j]=min(d[i][j],d[i][k]+d[k][j])
    if"o@"==a[i]+a[j]:r=t
 return-1if r>9**9else r

Function f takes a list of strings and returns the number of shots.
Test suite:
def test(s,r):
 print"ok"if f(s.split())==r else"fail"

test("o # @", -1)
test("......@.. .....##.. ......... ......o..", 2)
test("o....@", 1)
test("o.#.@", -1)
test("o..# ..#@", 2)
test("o#...# .#.#.# ...#.@", 4)
test("o### #..# ###@", 3)
test("o.## ##.@", 1)
test("...o .@#.", 2)