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
TIMAI2
January 11, 2024, 5:24pm
2
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 and get Not Solvable into Label2.
TIMAI2
January 11, 2024, 7:49pm
4
Odd, that shouldn't work (I expected [object][Object]
) but hey ho, away we go
Thanks to @TIMAI2 , the javascript solution is part of
"
A JavaScript inversions algorithm now attempts to determine if a 3 x 3 sliding puzzle is solvable . The tool is now part of Slide Nine (SlideNine_solvable.aia ). I am not sure how robust the article algorithm is; it appears to be reliable.
A forecast of solvability is automatically provided at the start of the puzzle. Also check if a move within a solvable puzzle leaves the puzzle still solvable or not. Use the 'S' button to find out if a move you just made still allows the puzzle to be…
SteveJG
Closed
January 19, 2024, 4:43pm
6
This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.