我试图在JavaScript中对称拆分一个字符串。我的意思是,如果它是8个字符,那么把它分成块2。如果它是9个字符,则分成3个字符。如果它是n个字符,那么将它分成2和3的块,这样它在中间形成一个镜像。
const segmentNumber = (value) => {
let array = value.split('')
if (array.length % 3 === 0) {
return chunkArray(array, 3).join('·')
} else if (array.length % 2 === 0) {
return chunkArray(array, 2).join('·')
} else {
let reversed = array.slice().reverse()
let a = 0
let ar = []
let zr = []
while (true) {
ar.push(array.slice(a, a + 2).join(''))
zr.push(reversed.slice(a, a + 2).join(''))
array = array.slice(a + 2)
reversed = reversed.slice(a + 2)
a += 2
let modulus
if (array.length % 3 === 0) {
modulus = 3
} else if (array.length % 2 === 0) {
modulus = 2
}
if (modulus) {
return ar.concat(chunkArray(array, modulus)).concat(zr.reverse())
}
}
}
return
}
function chunkArray(arr, len) {
var chunks = [],
i = 0,
n = arr.length;
while (i < n) {
chunks.push(arr.slice(i, i += len));
}
return chunks;
}我可以把绳子分块,但不知道如何使它对称地分块。例如:
你是如何产生这种模式的,在这种模式中,较小的数字在外面,而较大的数字3朝向中心,所以它形成了一个镜像?
如何改进我正在实现的内容?
发布于 2022-05-04 02:58:34
这符合你的产量吗?我不确定您的输入是什么,所以我只对您提供的示例值进行了测试。
function segmentNumber(length) {
let outside = 0;
if (length < 6)
return 'Only 6 and greater';
if(length % 3 == 0)
return new Array(length / 3).fill(3).join('-');
else {
while(length % 3 != 0 && length > 6) {
outside++;
length = length - 4;
}
if(length == 4)
return new Array(Math.floor(++outside * 2)).fill(2).join('-');
else
return [...new Array(outside).fill(2),
...new Array(Math.floor(length / 3)).fill(3),
...new Array(outside).fill(2)].join('-');
}
}
console.log(segmentNumber(10))
console.log(segmentNumber(11))
console.log(segmentNumber(12))
console.log(segmentNumber(13))
发布于 2022-05-04 03:09:18
这将为大于6的数字产生模式,并且在外部总是至少有一个'2‘(9除外)。
const splitter = n => {
if (n < 7) {
throw 'bad'
}
let twos = 0;
let threes = Math.ceil(n / 3);
// 9 is an edge case
if (n !== 9) {
let remain;
do {
--threes;
remain = n - threes * 3;
} while (remain % 4);
if (threes < 0) {
threes = n / 3;
remain = 0;
}
twos = remain / 4;
}
return `${'2'.repeat(twos)}${'3'.repeat(threes)}${'2'.repeat(twos)}`.split('');
}
for (let i = 7; i < 50; ++i) console.log(i, splitter(i).join('-'))
嗯,我看你不是所有的案子都有2的。
简单的改变..。
const splitter = n => {
if (n < 7) {
throw 'bad'
}
let twos = 0;
let threes = Math.floor(n / 3) + 1;
// 9 is an edge case
let remain;
do {
--threes;
remain = n - threes * 3;
} while (remain % 4);
if (threes < 0) {
threes = n / 3;
remain = 0;
}
twos = remain / 4;
return `${'2'.repeat(twos)}${'3'.repeat(threes)}${'2'.repeat(twos)}`.split('');
}
for (let i = 7; i < 50; ++i) console.log(i, splitter(i).join('-'))
发布于 2022-05-04 03:15:40
function segmentNumber(value)
{
for (let i = 0; i <= value; i++)
{
d = (value - 3 * i)/4
if (d >= 0 && d == parseInt(d))
{
return Array(d).fill(2).concat(Array(i).fill(3), Array(d).fill(2))
}
}
}https://stackoverflow.com/questions/72107318
复制相似问题