I’ll try to recreate that function based on what you said in:
The function must generate and return a randomly generated vector with defined size from a selection made on the page where the user chooses 10, 100, 1000, 10000 or 100000 elements for the vector.
And I’ll also assume that arrays with more than 10 elements should not be shown to the user for reasons of presentation from what I’ve seen of their code.
Then I’ll break the problem in pieces:
- Create a function that generates an array of N random numbers
- Receive the array size of a user input
- Present (or not) the new vector to the user
I will try to leave it well explained so that you understand the reasons for my decisions:
1. a function that generates an array of N random numbers
The function below generates an array of the size defined by the argument tamanho
filled with random values between 0 and 99.
function gera_array(tamanho) {
// Cria o novo array
let novo_array = [];
// Popula o array
for (let i=0 ; i < tamanho ; i++) {
novo_array.push(Math.floor(Math.random() * 100))
}
// Retorna o novo array populado
return novo_array;
}
2. Receive the array size of a user input
To receive the value of a <input>
user will just convert the attribute input.value
for an integer and use it as parameter for the function gera_array
.
// Guarda a referência para o elemento HTML
let input_tamanho = document.querySelector("#tamanho")
// Converte `input.value` para inteiro
let tamanho = parseInt(input_tamanho.value, 10)
Note that I created a variable input_tamanho
keeping the reference to the HTML element. I did this because searching the DOM tree is computationally expensive for the browser, but as I saved your reference just use input_tamanho
whenever I need it without the browser having to search for the element in the DOM again.
Note: The hint to save the reference to the HTML element is not required, but everyone should do this and understand why.
3. Presenting (or not presenting) the new vector to the user
I will create a function that reads the array and returns a string to be placed in HTML as feedback for the user.
function array_to_string(array) {
if (array.length <= 10) {
return "[" + array.join(", ") + "]"
else {
return "Array muito grande para visualizar"
}
Now putting it all together we would have:
function gera_array(tamanho) {
let novo_array = [];
for (let i=0 ; i < tamanho ; i++) {
novo_array.push(Math.floor(Math.random() * 100))
}
return novo_array;
}
function array_to_string(array) {
if (array.length <= 10) {
return "[" + array.join(", ") + "]"
} else {
return "Array muito grande para visualizar"
}
}
// referências:
let input_tamanho = document.querySelector("#tamanho")
let btn = document.querySelector("#btn")
let resultado = document.querySelector("#resultado")
btn.addEventListener('click', function() {
let tamanho = parseInt(input_tamanho.value, 10)
let vetor = gera_array(tamanho)
resultado.innerHTML = array_to_string(vetor)
})
<input id="tamanho" type="number" value="10">
<button id="btn">Criar array</button>
<p id="resultado">Resultado...</p>
Hello @Galbert22, Welcome to Sopt, before you start a look at our [Tour]. On your question whether your intention is to return a
Array
with these values, it seems to me that this missing open and close conchete, leaving +/- like thisreturn [ tamanho, vet1, vet2, vet3 ];
, for this reason I am signaling as typo =D– Icaro Martins
In addition, the
vet1 = [], vet2 = [], vet3 = []
is over-writing the parametersvet1
,vet2
andvet3
. Is that really what you want to do? And more:Valeatório
is not a valid function name in Javascript, as it includes an accent (ó
).– Luiz Felipe
I ended up modifying the code in the meantime, I will edit the main post leaving it as is. Using the brackets to return the value did not help and, yes, overwrite the parameters whenever the function is called is what I would like to do.
– Galbert22
Could you edit your question again to add the HTML code snippet that is required for the code to work? If possible, add a snippet executable.
– Luiz Felipe
Its conditions do not cover all possibilities, if
tamanho
is negative the function returns nothing, and apparently you expect your function to always return something. Another thing, so you get the argumentvet
if you will always overwrite it every function call? You could just create an empty array when you need it and that’s it.– fernandosavio
Why do you return [vet], and not vet?
– bfavaretto
You should also note that
input.value
returns a string, so you should do the integer conversion before using it for comparisons. You can use the methodparseInt(input.value, 10)
(I always use the 2nd parameter, Radix, to ensure that the browser does not interpret zero-started numeric strings as octal)– fernandosavio
Also... what is the need for
parseInt
in theMath.random()
, that already returns an integer? (In:parseInt(Math.random() * 100)
)– Luiz Felipe
Luiz,
Math.random()
returns a float.– fernandosavio
And it would be better to use the function
Math.floor()
with Random, the mathematical operation is more efficient than the whole string Parsing process. Ex.:Math.floor(Math.random() * 100);
– fernandosavio
Anyway Galbert22, there is a lot that can be improved in your function, only you can not simply change your code to what I think is best. It would be nice if you explained what this function should do and what the result of it will be used for. That way we could help you much more quickly and effectively.
– fernandosavio
I edited again the original post with information on the usefulness of this interview, thanks @fernandosavio for the tip.
– Galbert22
As I said in the post, if I don’t clear the vector when the function is called, it returns without any problem. But cleaning is necessary to not accumulate the numbers whenever it is going to generate the random.
– Galbert22