I want to use Mathematica to generate a random matrix with given dimensions, entries coming from a finite set, and with a determinant also coming from a finite set. (It's very important that the generation of this matrix is random. Ideally this process would give the same results as making a list of all matrices of the given size and possible entries with one of the acceptable determinants, and picking one at random.)
Some implementations of this are easy. To solve the 2x2 case with determinant == 1, and integral entries from -10 to 10, I can enter
Solve[{a d - b c == 1, -10 <= a <= 10, -10 <= b <= 10, -10 <= c <= 10, -10 <= d <= 10}, {a, b, c, d}, Integers]
But this doesn't easily extend to the problem of having broader sets of possible entries, e.g. a, b, c, and d being from -20 to 15, and being fractions with denominator between 1 and 10. That isn't essential, but the following condition is: I only need one random matrix, and I need it quickly -- but Mathematica takes forever via the above trick to generate all possible 3x3s. I thought of trying to use FindRoot together with seeding the process with random values, but I couldn't find control over
If there isn't a single function that will do the trick, I don't mind writing a function in Mathematica to do what I'm looking for -- but I'm very much a newbie to MM, so as much advice as you can give me would be greatly appreciated!
EDIT: As per gpap's excellent answer, here's the code that I've ended up with, modified from his answer to work with fractions.
det = Module[{i}, Sequence @@ (i /. Solve[Det[{{#1, #2, #3}, {#4, #5, #6}, {#7, #8, i}}] == 1, i]) &];
candidates = Apply[{##, det@##} &, RandomChoice[{0, 1/2, 1, 3/2, 2}, {10000, 8}], 2] // Quiet;
RandomChoice[Select[candidates, MemberQ[{0, 1/2, 1, 3/2, 2}, Last@# ] &]];