Home > other >  Separate numbers from array and order them, if there are consecutive 0's, put X [closed]
Separate numbers from array and order them, if there are consecutive 0's, put X [closed]

Time:09-25

  • There is an arrangement with a list of numbers, which can be of any size.

  • These are divided into blocks with the number zero, which marks the beginning and end of this and another block.

  • A zero at the beginning and end of the block would imply that there are no elements.

  • These blocks also need to be sorted in ascending order.

  • When printing the sequences must be separated by a space.

  • If there is a sequence of zeros when printed it should be represented by an X.

    Example 1: [1,3,2,0,7,8,1,3,0,6,7,1]

    The result: 123 1,378 167

    Example 2: [2,1,0,0,3,4]

    The result: 12X34

I need help in guiding how to solve this algorithm

var indices = [1,3,2,0,7,8,1,3,0,6,7,1] 

for (var i=0; i < indices.length; i  ) {
  
  if(indices[i] == 0) {
    console.log(i)
  }
  
}
console.log(indices);

CodePudding user response:

You have to go through series of consecutive steps to achieve the desired result.

function separateNumber(arr) {
  return arr
    .join("")
    .replace(/(0)\1 /g, "0X0")
    .split("0")
    .map((s) => s.split("").sort().join(""))
    .join(" ")
    .replace(/ X /g, "X");
}

console.log(separateNumber([1, 3, 2, 0, 7, 8, 1, 3, 0, 6, 7, 1]));
console.log(separateNumber([2, 1, 0, 0, 3, 4]));
console.log(separateNumber([2, 0, 1, 0, 0, 3, 4]));
console.log(separateNumber([2, 1, 0, 0, 3, 4, 0, 0, 0]));

CodePudding user response:

this way ?

const separate = arr => arr.reduce((r,v,i,{[i 1]:n})=>
  {
  if (v>0)   r.a.push(v)
  if ((v===0 || isNaN(n)) && r.a.length > 0)
    {
    r.a.sort((x,y)=>x-y)
    r.s.push( r.a.join(''))
    r.a.length = 0
    } 
  if (v===0) r.s.push(v)

  return isNaN(n) ? r.s.join('').replace(/00/g,'X').replace(/0/g,' ') : r
  },{s:[],a:[]})


test([1,3,2,0,7,8,1,3,0,6,7,1])
test([2,1,0,0,3,4])

function test ( arr)
  {
  console.log('\n',JSON.stringify(arr),'\n --->',separate(arr),'\n')
  }

  • Related