简体   繁体   English

将数字交替排列成两行

[英]Alternate numbers into two rows

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.我想我脑子放屁了,因为我想不出一个简单的公式来将数字序列按特定顺序排序,这样每张纸就可以打印 2 个数字(一个数字在一半和第二个数字在后半部分),所以当打印的一叠纸切成两半,将数字分开,然后将这两半放在一起时,数字就会按顺序排列。

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:所以,假设我有 5 个数字:3、4、5、6、7,预期结果将是 3、6、4、7、5 或 0、1、2、3、4、5、6、7变成 0,4,1,5,2,6,3,7 我的思维过程是:

  1. create a loop from 0 to total number of numbers创建一个从 0 到数字总数的循环
  2. if current step is even, then add to it total numbers divided in 2如果当前步骤是偶数,则将除以 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这是我目前所拥有的,如果起始编号设置为 1 或 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>

PS Sorry, about the title, couldn't come up with anything better to summarize this. PS 抱歉,关于标题,无法想出更好的总结。

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如果使用长度和索引向右移动 1 为奇数(例如除以 2 并获得 integer 值),或者
  • 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]));

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM