How to receive an array and return another

Asked

Viewed 3,540 times

-1

I have the following question:

We need a function more less that takes an array and returns another with the following three numbers:

in the first position, the fraction of numbers that are positive in second position, the fraction of numbers that are zero at the last position, the fraction of numbers that are negative For example, more([1, 2, 0, -1]) should return [0.5, 0.25, 0.25], because there are 50% positives, 25% zeros, and 25% negatives.

TIP Some questions that could help: How could I pass an array and ask each element if it is positive, negative or zero? How could I account for the elements? How to build the resulting array with these values?

  • Welcome to Stackoverflow in English. I edited your question to remove the greetings as we usually keep the text as clean as possible to focus on your scheduling question. If you are interested in visiting a part of the site that is not aimed to ask questions can know the [chat]. If you have questions about the operation, rules and procedures of the site visit the [meta] :)

3 answers

4

Welcome to the community and to the vast world of programming. Follow the solution with explanations:

var numeros = [1, 2, 0, -1]; //O Array de números fornecido pela questão
maisMenos(numeros); //Enviando o array para a função

function maisMenos(numeros) {
  /* Utilizando a função 'length' para obter a quantidade de elementos
  do array recebido como parâmetro */
  var quantidade = numeros.length;

  //Inicializando os contadores 
  var positivos = 0;
  var zeros = 0;
  var negativos = 0;

  /*Percorrendo cada elemento do array para verificar se é um número
    positivo, negativo ou zero */
  for (i = 0; i < quantidade; i++) {
    if (numeros[i] > 0) {
      positivos = positivos + 1; //Caso seja positivo, some mais 1
    } else if (numeros[i] < 0) {
      negativos = negativos + 1; //Caso seja negativo, some mais 1
    } else {
      zeros = zeros + 1; //Caso seja zero, some mais 1
    }
  }

  //Calculando as frações
  positivos = positivos / quantidade;
  zeros = zeros / quantidade;
  negativos = negativos / quantidade;
  
  //Criando o novo array que exibirá os resultados fracionados
  var array = [positivos, zeros, negativos];

  //Exibindo o array com os resultados no console do navegador
  console.log(array);

  return array;
}

  • Thanks my friend ! worked perfectly !

  • 2

    @By what you are saying, it seems to be the case to mark an answer as accepted. If you have an answer that really helped you, mark it as accepted. If you arrived at the solution yourself, post the solution as an answer. So content is more organized and easier to find in the future by other people with similar problems.

0

Follow the answer. Receives the outgoing array variable and returns an outgoing array (not played inside a variable, but it is quite simple).

function inverterArray(arrayEntrada) {
    var totalElementos = arrayEntrada.length;
    var fracaoPositivo = 0;
    var fracaoNegativo = 0;
    var fracaoNula = 0;

    // Como poderia contabilizar os elementos
    arrayEntrada.forEach(function(valor) {
        if (valor > 0) {
            fracaoPositivo++;
        } else if (valor < 0) {
            fracaoNegativo++;
        } else {
            fracaoNula++;
        }
    });

    // Como construir o array resultante com estes valores
    return [(fracaoPositivo / totalElementos), (fracaoNula / totalElementos), (fracaoNegativo / totalElementos)];
}
  • Thank you my friend, it worked perfectly!

0

Another way to solve this is by using the Math.sign() javascript, would be a resolution similar to our friend above. Follow the example:

let valores = [1,2,0,-1];
let positivos = [];
let negativos = [];
let nulos = [];
let tamanho = valores.length;

for (let i = 0; i < tamanho ; i++) {
    let x = Math.sign(valores[i]);
    if (  x == 0  ) {
        nulos.push(i);
    } else if ( x == 1 ) {
        positivos.push(valores[i]);
    } else {
        negativos.push(valores[i]);
    }
}

let resposta = [(positivos.length/tamanho) , (negativos.length/tamanho) , (nulos.length/tamanho)];

Browser other questions tagged

You are not signed in. Login or sign up in order to post.