I have this .txt file to change to a nested array:
000011000000
000100001100
000001100001
010010001000
100101000100
101010010001
001000001001
000001000111
010100100010
010010010010
000000011100
001001110000
to the format:
var data = [
[0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 1, 0, 0, 0, 0, 1, 1, 0, 0],
[0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 1],
[0, 1, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0],
[1, 0, 0, 1, 0, 1, 0, 0, 0, 1, 0, 0],
[1, 0, 1, 0, 1, 0, 0, 1, 0, 0, 0, 1],
[0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 1],
[0, 0, 0, 0, 0, 1, 0, 0, 0, 1, 1, 1],
[0, 1, 0, 1, 0, 0, 1, 0, 0, 0, 1, 0],
[0, 1, 0, 0, 1, 0, 0, 1, 0, 0, 1, 0],
[0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 0, 0],
[0, 0, 1, 0, 0, 1, 1, 1, 0, 0, 0, 0]
]
what I have done so far is:
- Read the file:
function readMatrixFile(){
var inputElement = document.getElementById("adjencyMatrixInput");
var fileList = inputElement.files;
var plainMatrix = new FileReader();
plainMatrix.readAsText(fileList[0]);
plainMatrix.onload = function () {
//Add to Matrix
renderMatrix(plainMatrix)
}
}
and 2. Split the File
function renderMatrix(plainMatrix) {
var matrix = plainMatrix.result;
var mtx = [];
matrix = matrix.split("\n");
}
I know I need to push through a for loop, but not sure how to get the nested array.
CodePudding user response:
Split the string by a newline, then map over each item and convert the string into an array of characters with spread syntax.
const str = `000011000000
000100001100
000001100001
010010001000
100101000100
101010010001
001000001001
000001000111
010100100010
010010010010
000000011100
001001110000`
const res = str.split("\n").map(e => [...e])
console.log(res)
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>
To convert the characters to numbers, map over the array of characters and parse each item:
const str = `000011000000
000100001100
000001100001
010010001000
100101000100
101010010001
001000001001
000001000111
010100100010
010010010010
000000011100
001001110000`
const res = str.split("\n").map(e => [...e].map(e => e))
console.log(res)
<iframe name="sif2" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>
CodePudding user response:
You turn matrix
into a a string of ones and zeros, you just need to split the string and convert them to numbers
function renderMatrix(plainMatrix) {
var matrix = plainMatrix.result;
var mtx = matrix.split("\n"); // mtx is now an array of strings of ones and zeros
mtx = mtx.map(string => string.split('')); // mtx is now an array of arrays of number string
mtx = mtx.map(nested => nested.map(numberString => Number(numberString))); // mtx is now what you want
}