Counter every time an IF - ELSE conditional is used?

0

I need to do a simple counter for an IF-ELSE conditional, the question is simple: my code goes through the numbers from 100 to 999 and determines which are of increasing, decreasing and mixed composition.

Example:

creciente=159  
decreciente=851  
mixto=253

To know this relationship I use an IF-ELSE, what I have to do is an accountant that every time a if is used, the idea is to build an accumulator each time a specific condition is met, and then use that accumulator and get a percentage of the decreasing and mixed growing numbers.

function DeterminaNumeros(numero) {
  var num = numero.toString()
  var a = num.split(''); // separa los digitos y los convierte en matriz
  for (x = 0; x < a.length; x++) {
  }
  if (x == 3) {
    if (a[0] >= a[1] && a[1] >= a[2]) {
      //----------------------------------------------
      var acum3 = 1;
      var suma = 0;
      var valor = 0;
      while (acum3 <= 5) {
        valor = parseInt(valor);
        suma = suma + valor;
        acum3 = acum3 + 1;
      }

      //document.write('decreciente ');
      //-------------------------------------------------
    } else {
      if (a[0] <= a[1] && a[1] <= a[2]) {
        document.write('creciente ');

      } else {
        var acum3 = 0;
        document.write('Numero Mixto ');
      }
    }

  }
}

N = 99;
do {
  N = N + 1;
  var resultado = DeterminaNumeros(N);
  document.write(resultado + '<br>');
  document.write(N);
} while (N < 1001);
    
asked by Yader Yepez 22.11.2018 в 05:01
source

3 answers

2

Taking your code and modifying it, I propose the following:

function DeterminaNumeros(numero) {
    var num = numero.toString()
    var a = num.split(''); // separa los digitos y los convierte en matriz
    if (a.length == 3) {
        if (a[0] >= a[1] && a[1] >= a[2]) {      
            decrecientes++;
            return "decreciente";
        } else {
            if (a[0] <= a[1] && a[1] <= a[2]) {
                crecientes++;
                return "creciente";
            } else {
                mixtos++;
                return "mixto";
            }
        }
    }
}

var crecientes=0;
var decrecientes=0;
var mixtos=0;

var totalNumeros=0;
for(var i=100;i<=999;i++){
    totalNumeros++;
    var resultado = DeterminaNumeros(i);
    //document.write(N +" es " + resultado +"<br>");
}
document.write(totalNumeros + " números<br>");
document.write(crecientes + " son crecientes ("+ crecientes*100/totalNumeros +"%)<br>");
document.write(decrecientes + " son decrecientes ("+ decrecientes*100/totalNumeros +"%)<br>");
document.write(mixtos + " son mixtos ("+ mixtos*100/totalNumeros +"%)<br>");

I have removed the for loop that you used to check the length of the numbers since it did not make sense when you already have it with a.length

I have eliminated those variables as value, sum and accum3 because I can not see why you want them if you do not use them at all.

I changed the Do-While loop by a for loop for efficiency and simplicity.

I added that the function returns the type of number.

Finally I added the calculation of the percentages at the end.

The results are:

900 numbers
156 are growing (17,333333333333332%)
219 are decreasing (24.333333333333332%)
525 are mixed (58.333333333333336%)

I hope it's what you needed.

As for the conditions of the if, if they are numbers with the 3 identical figures, they could be considered increasing or decreasing indistinctly, although now they will always be considered as decreasing since it is the first if.

    
answered by 22.11.2018 в 10:51
2

If I have understood you correctly, you want to obtain the strictly increasing numbers, the decreasing and mixed numbers and calculate the percentage of each of them. In that case you do not need to complicate yourself so much. I leave you two solutions. One without using ES6 and another with ES6

Without ES6

var sumCrec = 0;
var sumDec = 0;
var sumMixto = 0;
function DeterminaNumeros(numero){
        var num=numero.toString()
        var a=num.split(''); // separa los digitos y los convierte en matriz     
            if (a[0]>=a[1] && a[1]>=a[2]) { 
              sumDec++;
            }else{
              if (a[0]<=a[1] && a[1]<=a[2]) {
                sumCrec++;
              }else{
                sumMixto++;
              }
    }
}
var N=100;
var aux = N;
    do{        
        DeterminaNumeros(aux);  
		aux++;		
    }while(aux<1001);

	document.write('Crecientes: ' + sumCrec + '/' + (aux-1-N) + '(' + Number(sumCrec/(aux-1-N) *100) +'%)'+'<br>');
	document.write('Decrecientes: ' + sumDec + '/' + (aux-1-N) + '(' + Number(sumDec/(aux-1-N) *100) +'%)'+'<br>');
	document.write('Mixtos: ' + sumMixto + '/' + (aux-1-N) + '(' + Number(sumMixto/(aux-1-N) *100) +'%)'+'<br>');
	document.write('<hr/>');

var sumCrec = 0;
var sumDec = 0;
var sumMixto = 0;
var Ninic=100;
var N=1001;
var arrCrec = [];
var arrDecrec = [];
var arrMixto = [];

//Esta es una forma de generar un array de enteros añadiendo el símbolo iterator al prototype del tipo Number (utilizamos generadores)
Number.prototype[Symbol.iterator] = function*(){
		for(let i=Ninic;i<this;i++){
			  yield i;    
		}
	}

determinaNumerosES6(N);	

	function determinaNumerosES6(numero){
    //Obtenemos el array de enteros desde la Ninic hasta el número indicado
		let arr = [...numero];
    //Por cada valor comprobamos cómo está ordenado
		  arr.forEach((val)=>{
		  howIsSorted(val.toString());
		});
		
		document.write('Crecientes: ' + sumCrec + '/' + (N-1-Ninic) + '(' + Number(sumCrec/(N-1-Ninic) *100) +'%)'+'<br>');
    document.write(arrCrec + '<br/>');
    document.write('<hr/>');
		document.write('Decrecientes: ' + sumDec + '/' + (N-1-Ninic) + '(' + Number(sumDec/(N-1-Ninic) *100) +'%)'+'<br>');
    document.write(arrDecrec + '<br/>');
    document.write('<hr/>');
		document.write('Mixtos: ' + sumMixto + '/' + (N-1-Ninic) + '(' + Number(sumMixto/(N-1-Ninic) *100) +'%)'+'<br>');
    document.write(arrMixto + '<br/>');
		document.write('<hr/>');
	}

function howIsSorted(num){
  let aux = num.split('');
  //Ascendentes --> Sumamos y guardamos en array (por si queremos ver los valores que cumplen la condición)
  if(isAscending(aux)){
    sumCrec++;
    arrCrec.push(num);
  }
  else if(isDescending(aux)){
    sumDec++;
    arrDecrec.push(num);
  }
  else{
    sumMixto++;
    arrMixto.push(num);
  }
}

//Hacemos una copia del array de entrada con slice desde el índice 1. A continuación con map creamos un nuevo array cuyos valores serán el resultado de la función de comprobación (e>=a[i]). Así obtendremos un array con [true, true, false, o lo que sea, según se cumpla la función o no). Por último, con every devolvemos true o false si todos los elementos del array son iguales en este caso (todo trues querrá decir que está ordenado de forma ascendente.
function isAscending(a){ 
return a.slice(1)
    .map((e,i) => e >= a[i])
    .every(x => x);
}
              
//Lo mismo que isAscending pero con orden descendiente
function isDescending(a){
	return a.slice(1)
    .map((e,i) => e <= a[i])
    .every(x => x);
 }
    
answered by 22.11.2018 в 10:58
-1

What I can think of is to declare the counters outside the function Determine Numbers by returning them globally and then place an increment of these within each if, being as follows.

var countCreciente = 0;
var countDecreciente = 0;
var countMixto = 0;
function DeterminaNumeros(numero) {
      
  var num = numero.toString()
  var a = num.split(''); // separa los digitos y los convierte en matriz
  for (x = 0; x < a.length; x++) {
  }//for (x = 0; x < a.length; x++)
  if (x == 3) {
    if (a[0] >= a[1] && a[1] >= a[2]) {
      //----------------------------------------------
      var acum3 = 1;
      var suma = 0;
      var valor = 0;
      while (acum3 <= 5) {
        valor = parseInt(valor);
        suma = suma + valor;
        acum3 = acum3 + 1;
      }//while (acum3 <= 5)
      countDecreciente++;
      //document.write('decreciente ');
      //-------------------------------------------------
    } else {
      if (a[0] <= a[1] && a[1] <= a[2]) {
        document.write('creciente ');
        countCreciente++;
      } else {
        var acum3 = 0;
        countMixto++;
        document.write('Numero Mixto ');
      }//else
    }//else

  }//if (x == 3)
}//DeterminaNumeros


N = 99;
do {
  N = N + 1;
  var resultado = DeterminaNumeros(N);
  document.write(resultado + '<br>');
  document.write(N);
} while (N < 1001);
document.write('<br>Total crecientes: ' + countCreciente + '<br>');
document.write('Total decrecientes: ' + countDecreciente + '<br>');
document.write('Total mixtos: ' + countMixto + '<br>');
    
answered by 22.11.2018 в 11:07