Home > Software engineering >  Alternate numbers into two rows
Alternate numbers into two rows

Time:04-09

I think I'm having a brain fart, because I can't figure out a simple formula to be able sort a sequence of number into specific order so it can be printed 2 numbers per sheet of paper (one number on one half and second number on second half), so when the printed stack of paper cut in half, separating the numbers, and then these halves put together, the numbers would be in sequence.

So, let's say I have 5 numbers: 3,4,5,6,7, the expected result would be 3,6,4,7,5 or 0,1,2,3,4,5,6,7 would become 0,4,1,5,2,6,3,7 My thought process is:

  1. create a loop from 0 to total number of numbers
  2. if current step is even, then add to it total numbers divided in 2

Obviously, I'm missing a step or two here, or there is a simple mathematical formula for this and hopefully someone could nudge me in a right direction.

This is what I have so far, it doesn't work properly if start number set to 1 or 3

function show()
{
  console.clear();
  for(let i = 0, count = end.value - start.value, half = Math.round(count/2); i <= count; i  )
  {
    let result = Math.round(( start.value   i) / 2);
    if (i && i % 2)
      result = result   half -1;
   
    console.log(i, "result:", result);
  }
}

//ignore below
for(let i = 0; i < 16; i  )
{
  const o = document.createElement("option");
  o.value = i;
  o.label = i;
  start.add(o);
  end.add(o.cloneNode(true));
}

start.value = 0;
end.value = 7;

function change(el)
{
  if ( start.value >  end.value)
  {
    if (el === start)
      end.value = start.value;
    else
      start.value = end.value;
  }
}
<select id="start" oninput="change(this)"></select> -
<select id="end" oninput="change(this)"></select>
<button onclick="show()">print</button>

P.S. Sorry, about the title, couldn't come up with anything better to summarize this.

CodePudding user response:

You could get the value form the index

  • if odd by using the length and index shifted by one to rigth (like division by two and get the integer value), or
  • if even by the index divided by two.

function order(array) {
    return array.map((_, i, a) => a[(i % 2 * a.length   i) >> 1]);
}

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

  • Related