My teacher gave us a lesson where we had to find out how many times a x number was drawn in the lottery. He gave us a .txt document containing all datas from the previous years. He told us to build a function to discover these values. I ended up with this:
//Transfer the txt logs to variable 'conteudo'
try {
conteudo = fs.readFileSync("dados.txt", "utf8");
conteudo = conteudo.split("\r\n");
vezessort = 0;
} catch(erro) {
console.error(erro.message);
}
//Function created to review all the lines in the txt file
//First for loop is to split each line, making them an array
//Second loop is to compare the values 2 to 7 on each line, where contains the numbers drawn in the lottery
function vezSort(a){
for (i = 1; i < conteudo.length; i ){
conteudo[i] = conteudo[i].split(";");
for(j = 2; j < 8; j ){
if(conteudo[i][j] == a){
vezessort = 1;
}
}
}
}
//In this exercise we need to capture the input from user, and use it as a parameter on the function
a = parseInt(prompt('Digite um número: '));
r = vezSort(a);
console.log(`O número foi sorteado ${vezessort} vezes.`);
It works perfectly, the final values matches with the desired output he gave. The problem is, in the next question he tell us to loop the function for each number between 1 to 60. But every attempt I try to loop I get problems with this line: conteudo[i] = conteudo[i].split(";");
. What I am doing wrong? (Btw, in this exercise the input from the user is not needed.)
CodePudding user response:
The problem is that you're modifying the conteudo
array when you call vezSort()
. It's initially an array of strings, but you're changing it to a 2-dimensional array when you do conteudo[i] = conteudo[i].split(";");
You should either convert it to a 2-dimensional array just once, outside the vezSort()
function, or use a local variable rather than modifying the original array.
Doint it once is more efficient, so that's how I show it:
try {
conteudo = fs.readFileSync("dados.txt", "utf8");
conteudo = conteudo.split("\r\n");
conteudo = conteudo.map(line => line.split(';'));
vezessort = 0;
} catch(erro) {
console.error(erro.message);
}
//Function created to review all the lines in the txt file
//First for loop is to split each line, making them an array
//Second loop is to compare the values 2 to 7 on each line, where contains the numbers drawn in the lottery
function vezSort(a){
for (i = 1; i < conteudo.length; i ){
for(j = 2; j < 8; j ){
if(conteudo[i][j] == a){
vezessort = 1;
}
}
}
}
CodePudding user response:
.split()
turns a string into an array of substrings, not an array into a string. For that, use .join()
.
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/split https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/join