How to make this javascript code using a matrix work with App Inventor to count matrix inversions?

How to make this javascript code using a matrix work with App Inventor to count matrix inversions.

javascript matrix inversion source and example:

Solvable and unsolvable matrix situations incorrectly report as Solvable in App Inventor. A matrix inversion of [[8, 1, 2],[5, 4, 3],[7, 6, 0]] correctly reports unsolvable (odd number of inversions counted) (when run in JSFiddle but not in AI where 0 inversions are counted.

What am I missing? Advice would be appreciated.

Here us what I have:

matrixSNjavascript.aia (3.2 KB)

Thanks for any advice.
-- Steve

1 Like

Try like this in html/js (not tested):
Note the conversion of the webviewstring to an array object - puzzleObj.

// This function returns true 
// if given 8 puzzle is solvable. 
function isSolvable(puzzleObj) { 
	// Count inversions in given 8 puzzle 
	let invCount = getInvCount(puzzleObj);
	// return true if inversion count is even. 
	return (invCount % 2 == 0);
}

// Driver code

// Value 0 is used for empty space

puzzle = window.AppInventor.getWebViewString();
puzzleObj = JSON.parse(puzzle);
document.write("matrix: " + puzzle)

document.write("inversions: " +getInvCount(puzzle));

//unsolvable
//puzzle = [[8, 1, 2],[5, 4, 3],[7, 6, 0]] ;

//puzzle = [[8, 1, 2],[0, 4, 3],[7, 6, 5]] ;
// puzzle = [[1, 8, 2],[0, 4, 3],[7, 6, 5]] ;

if(isSolvable(puzzleObj)) {
	document.write("Solvable");
        //document.write(inv_count);
}
else {
	document.write("Not Solvable");
}	
1 Like

Thanks for quick response Tim. Your code needs a little help to produce a correct solution Not Solvable.

puzzle = window.AppInventor.getWebViewString();
puzzleObj = JSON.parse(puzzle);
puzzle = puzzleObj;
document.write("matrix: " + puzzle)


Now on AI I get :
3 inversions : 8,1,2,5,3,7,6 Not Solvable which is the same solution shown with JSFiddle.

Your hint helped solve the code, now I need to make it look pretty :wink: and get Not Solvable into Label2.
solutionpart

Odd, that shouldn't work (I expected [object][Object]) but hey ho, away we go :wink:

Thanks to @TIMAI2 , the javascript solution is part of :wink:

"

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.