Separate sequences when a value is repeated - Javascript

0

We want to make a program that receives a sequence of integers, the first of which will indicate the number of numbers to be read, and order the sequences.

When we find a sequence we will order, from least to greatest, all the elements belonging to that sequence. Once all the sequences are ordered, all the numbers ordered in their sequences will be shown on the screen.

 Entradas
 9 5 4 3 6 3 7 1 7 5
 Salidas
 3 4 5 6 1 3 7 5 7

This is what I take to the moment but what I try to do does not work

   let cad = [];//SECUENCIAS
   let numero = Number(prompt("Numero"));
   let cad1 = new Array(numero);
   for (let i=0;i<numero;i++){
   cad[i] = Number(prompt('Numero ${i+1}'));}

   for (let i=0;i<numero;i++) {
   for (let j=0;j<numero;j++){
   while (cad1[i].indexOf(cad[j])<1){
   cad1.push(cad[j]);}
   }}

I want that at the moment of finding a repeated cut there, I ordered it and continued with the same cycle where I stayed and store the sequences together to print them.

¡EDIT !!: I need that if it is already 5,4,3,6 (the following is a 3, so it is not added because it is repeated) then I order and it remains 3,4,5,6 and start again from 3 and it is 3,7,1 (because it follows 7 and does not enter because it is repeated) and now I order 1,3,7 and to finish I order the 5.7-- The "9" only represents how many numbers are going to enter. Thank you very much

    
asked by Vakker Livet 27.11.2018 в 02:46
source

2 answers

0

A simple way to keep track and check if you have a repeated number is to use an object as a dictionary ( { } ).

var numeros = [5, 4, 3, 6, 3, 7, 1, 7, 5];

var secuencia = {};
var grupos = [];

for (var i = 0; i < numeros.length; i++) {
  var n = numeros[i];
  
  if (secuencia[n]) {
    grupos.push(secuencia);
    secuencia = {};
  }
  
  secuencia[n] = true;  
}
grupos.push(secuencia);

console.log(grupos);

So far you have the groups separated within an array, now what you have to do is iterate it, extract the names of the properties and sort it.

    
answered by 27.11.2018 / 07:25
source
0

I'm not sure what you want to do with the loops but one way to organize numbers from lowest to highest would be:

      var points = [9, 5, 4, 3, 6, 3, 7, 1, 7, 5];
      points.sort(function(a, b){return a-b});

I hope it helps you;)

    
answered by 27.11.2018 в 04:42