-
1. Re: math / array / matrix-question
-hans- Dec 20, 2013 12:48 AM (in response to -hans-)Good morning,
splitted the sourcearray to its 'cols' and 'rows' to compare each with the resultarrays.
Solved
Hans
-
2. Re: math / array / matrix-question
Marc Autret Dec 20, 2013 11:54 PM (in response to -hans-)Hi Hans,
Just a quick note although your question is solved.
Provided that your matrix is 5×5 you could easily map any element to a single character in the set { A, B..., Z } (for example).
Then your problem can be reduced to some pattern matching algorithm, that is, finding the longest part of the input string within a 'flat string' that just concatenates the rows and the columns of the search matrix in the form ROW1|ROW2...|COL1|COL2...|COL5
And you can create RegExp on the fly to compute the solution(s) with almost no effort:
const MX_ORDER = 5; const MIN_MATCH = 3; // We need at least 3 contiguous items var bestMatrixMatch = function F(/*str[]*/ROWS, /*str*/ND) //-------------------------------------- // NB: No check is made on ROWS, so make sure you supply // MX_ORDER strings, each being MX_ORDER-sized { // Put in cache some subroutines // --- F.RES_TO_STR ||(F.RES_TO_STR = function() { return localize("'%1' found in %2", this.result, this.location); }); F.ROWS_TO_HS ||(F.ROWS_TO_HS = function(R, C,i,j) { for( i=0,C=[] ; i < MX_ORDER ; ++i ) for( C[i]='',j=0 ; j < MX_ORDER ; C[i]+=R[j++][i] ); return R.concat(C).join('|'); }); // Vars // --- var haystack = F.ROWS_TO_HS(ROWS), candidates = ND && haystack.match( new RegExp('['+ND+']{'+MIN_MATCH+',}','g') ), t, p; if( !candidates ) return null; // Sort the candidates by increasing size // --- candidates.sort( function(x,y){return x.length-y.length} ); // Grab the matches and keep the best // --- while( t=candidates.pop() ) { if( 0 > ND.indexOf(t) ) continue; p = 1+~~(haystack.indexOf(t)/(1+MX_ORDER)); return { result: t, location: (p<=MX_ORDER)?('Row #'+p):('Col #'+(p-MX_ORDER)), toString: F.RES_TO_STR, } } return null; } // ================= // Sample code // ================= var rows = [ "ABCDE", "FGHIJ", "KLMNO", "PQRST", "UVWXY" ]; var needle = "EKLMINSX"; // get the result // --- var result = bestMatrixMatch(rows, needle); alert( "Searching the longest part of '" + needle + "' in:\r\r" + ' '+rows.join('\r').split('').join(' ') + '\r\r===============\r\r' + (result || "No result.") );@+
Marc
-
3. Re: math / array / matrix-question
-hans- Dec 29, 2013 9:58 AM (in response to Marc Autret)Hi,
sorry for the late reply. works like a charm
Perhaps, some day I'll even understand how ... ;-)
Hans



