Skip to main content

list manipulation - Scramble matrix under some condition



Assume I have a matrix.


(mat = Partition[Range@9, 3]) // MatrixForm

mat=(123456789)


I would like to scramble matrix matcolunmn-wise to generate all possible new matrix newMat under some condition.




Conditions are:



1) Column elements of mat must stay in their column, i.e. 1st column of newMat must be one of the elements of the Permutations[{1, 4, 7}, {3}]={{1, 4, 7}, {1, 7, 4}, {4, 1, 7}, {4, 7, 1}, {7, 1, 4}, {7, 4, 1}}; And similarly col2 ∈ Permutations[{2,5,8}, {3}] and col3 ∈ Permutations[{3,6,9}, {3}].



2) 1st row of mat is {1,2,3} and thus 1st Row entries of newMat, should not contain any of element of this set= {{1, 2}, {1, 3}, {2, 3},{1,2,3}} i.e. pairs or triple. The same for row 2 and row 3.



...............


..................


{1,4,7} must stay in the 1st column, {2,5,8} must stay in the 2nd column, {3,6,9} must stay in the 3rd column. Every row has distinct colors.


....


.....


Some of the undesired newMat: It passes first condition but not second condition. enter image description here


For 3×3 there are only 3!2!1!= 12 matrices satisfies the condition which shows below. For 4×4 there are only 4!3!2!1!= 288 Good candidate:


newMat=(186429753)



I would like to generate all 4×4 square matrices and if possible/easy all 5×4 matrices (there are 5!4!3!2!=34560). Any suggestion.


Edit


After I used @yohbs code I was able to generate all desired matrices but it is not efficient for 4×4 matrices.


   {r, c} = Dimensions[mat];
perms = Permutations[Range@r];
q = 1 + IntegerDigits[Range[(r!)^c], r!, c];
allScrambles =
Transpose[
Table[mat[[perms[[q[[i, j]]]], j]], {j, c}, {i, Length@q}], {3, 1,
2}];



sub = Join @@ (Subsets[#, {2}] & /@ mat);

ArrayPlot[#,
ColorRules -> {1 | 2 | 3 -> Red,
4 | 5 | 6 -> Darker@Green, _ -> Blue},
Epilog -> {MapIndexed[
Text[Style[#1, White, 26], Reverse[#2 - 1/2]] &,
Reverse[#], {2}]}] & /@ sol


enter image description here



Answer



I must have something wrong with my understanding of the criteria because I get a lot more possibilities than what is shown.


Here is my solution:


ClearAll[MatrixOK, matrixSize, mat, sub, columns, columnPermutations, \
allPossibilities, okChoices]
MatrixOK2[matrix_, columns_] :=
Max[Length[#] & /@
Flatten[Outer[Intersection, mat, matrix, 1], 1]] <= 1;

matrixSize = {3, 3};
DateString[]
(mat = ArrayReshape[Range@(Times @@ matrixSize),
matrixSize]) // MatrixForm
sub = Subsets[#, {2, matrixSize[[2]]}] & /@ mat;
columns = Transpose@mat;
columnPermutations = Permutations[#, {matrixSize[[1]]}] & /@ columns;
allPossibilities = Transpose /@ Tuples[columnPermutations];
okChoices =
Select[allPossibilities, MatrixOK2[#, matrixSize[[2]]] &];

DateString[]
Length[allPossibilities]
Length[okChoices]
(* some examples *)
MatrixForm[#] & /@ Take[okChoices, 5]

Edit 2: For the 4x4 case, I get 331776 possibilities and 576 that meet what I think are the criteria. For 3x3, I get 216 possibilities and 12 solutions.


I believe the correct formula for the number of choices for an n by n array is


(Factorial[n])^n


This agrees with the choices that are computed for the 4x4 case. Or, for the case described above that has "matrixSize" describing the {rows, columns},


Factorial[matrixSize[[1]]]^matrixSize[[2]]

EDIT: I believe that there is another way to determine a matrix is OK using this (modified per new understanding):


MatrixOK2[matrix_, columns_] := 
Max[Length[#] & /@
Flatten[Outer[Intersection, mat, matrix, 1], 1]] <= 1;

It doesn't use or need columns but I kept it in for consistency with the previous formula. I'm somewhat surprised that this new formula isn't substantially faster but for 3x3, that isn't the case. For the 4x4, it lowers the wall clock time from 13 seconds to 5 seconds, so it is noticeably faster there. I've confirmed that the results "okChoices" are the same regardless of what check formula I use.


EDIT 2: I now understand that the criteria about not having repetitions of the original rows applies to ALL rows. So, I've modified the second check function to fix this and now get the same number as expected.



Comments

Popular posts from this blog

functions - Get leading series expansion term?

Given a function f[x] , I would like to have a function leadingSeries that returns just the leading term in the series around x=0 . For example: leadingSeries[(1/x + 2)/(4 + 1/x^2 + x)] x and leadingSeries[(1/x + 2 + (1 - 1/x^3)/4)/(4 + x)] -(1/(16 x^3)) Is there such a function in Mathematica? Or maybe one can implement it efficiently? EDIT I finally went with the following implementation, based on Carl Woll 's answer: lds[ex_,x_]:=( (ex/.x->(x+O[x]^2))/.SeriesData[U_,Z_,L_List,Mi_,Ma_,De_]:>SeriesData[U,Z,{L[[1]]},Mi,Mi+1,De]//Quiet//Normal) The advantage is, that this one also properly works with functions whose leading term is a constant: lds[Exp[x],x] 1 Answer Update 1 Updated to eliminate SeriesData and to not return additional terms Perhaps you could use: leadingSeries[expr_, x_] := Normal[expr /. x->(x+O[x]^2) /. a_List :> Take[a, 1]] Then for your examples: leadingSeries[(1/x + 2)/(4 + 1/x^2 + x), x] leadingSeries[Exp[x], x] leadingSeries[(1/x + 2 + (1 - 1/x...

mathematical optimization - Minimizing using indices, error: Part::pkspec1: The expression cannot be used as a part specification

I want to use Minimize where the variables to minimize are indices pointing into an array. Here a MWE that hopefully shows what my problem is. vars = u@# & /@ Range[3]; cons = Flatten@ { Table[(u[j] != #) & /@ vars[[j + 1 ;; -1]], {j, 1, 3 - 1}], 1 vec1 = {1, 2, 3}; vec2 = {1, 2, 3}; Minimize[{Total@((vec1[[#]] - vec2[[u[#]]])^2 & /@ Range[1, 3]), cons}, vars, Integers] The error I get: Part::pkspec1: The expression u[1] cannot be used as a part specification. >> Answer Ok, it seems that one can get around Mathematica trying to evaluate vec2[[u[1]]] too early by using the function Indexed[vec2,u[1]] . The working MWE would then look like the following: vars = u@# & /@ Range[3]; cons = Flatten@{ Table[(u[j] != #) & /@ vars[[j + 1 ;; -1]], {j, 1, 3 - 1}], 1 vec1 = {1, 2, 3}; vec2 = {1, 2, 3}; NMinimize[ {Total@((vec1[[#]] - Indexed[vec2, u[#]])^2 & /@ R...

plotting - Plot 4D data with color as 4th dimension

I have a list of 4D data (x position, y position, amplitude, wavelength). I want to plot x, y, and amplitude on a 3D plot and have the color of the points correspond to the wavelength. I have seen many examples using functions to define color but my wavelength cannot be expressed by an analytic function. Is there a simple way to do this? Answer Here a another possible way to visualize 4D data: data = Flatten[Table[{x, y, x^2 + y^2, Sin[x - y]}, {x, -Pi, Pi,Pi/10}, {y,-Pi,Pi, Pi/10}], 1]; You can use the function Point along with VertexColors . Now the points are places using the first three elements and the color is determined by the fourth. In this case I used Hue, but you can use whatever you prefer. Graphics3D[ Point[data[[All, 1 ;; 3]], VertexColors -> Hue /@ data[[All, 4]]], Axes -> True, BoxRatios -> {1, 1, 1/GoldenRatio}]