简体   繁体   English

实现此序列的最快方法?

[英]Quickest way to achieve this sequence?

I'm trying to create a simple algorithm that builds an array with a dynamic length. 我正在尝试创建一个简单的算法来构建具有动态长度的数组。

Then, it will, one by one, replace an item, and then two, then three and so on until the only items left are the first and last. 然后,它将一个接一个地替换一个项目,然后是两个,然后是三个,依此类推,直到剩下的唯一项目是第一个和最后一个。

like this: 像这样:

12345

1*345 // it never touches the first
12*45
123*5 // it doesn't ever touch the last item

1**45
12**5

1***5 // done, nowhere else to go

I put together a simple demo to show what I'm trying to do. 我整理了一个简单的演示来展示我要做什么。

var length = 6,
    array = [],
    log = document.getElementById("log"),
    edited,
    j,
    i;

for (i = 1; i <= length; i++) {
    array.push(i);
}

log.innerHTML += array.join(" ") + "<br><br>";

for (i = 1; i < (length - 1); i++) {
    edited = array.concat();
    for (j = i; j < (length - 1); j++) {
        edited[j] = "*";
        log.innerHTML += edited.join(" ") + "<br>";
    }
    log.innerHTML += "<br>";
}

Fiddle 小提琴

It works fine, the only problem is it's out of order. 它工作正常,唯一的问题是它出了故障。 Right now it seems to only iterate by number of asterisks, then by index. 现在,它似乎仅按星号进行迭代,然后按索引进行迭代。 I need it to do the opposite. 我需要它做相反的事情。

// it does this
12345

1*345
1**45
1***5

12*45
12**5

123*5 // out of order

If someone could help that would be great because I am really at a loss! 如果有人可以帮忙,那将是很好,因为我真的很茫然!

This should get it done. 这应该完成它。

var a = 6, // array length
    b = [], // array
    log = document.getElementById("log"),
    c,
    d,
    e;

for (c = 1; c <= a; c++) {
    b.push(c);
}

log.innerHTML += b.join(" ") + "<br><br>";

//the size of the asterisk chunk
for(i = 1; i < b.length - 1; i ++)
{
    //position to start asterisk chunk
    for(j = 1; j < b.length - i; j ++)
    {
        var tempArr = b.concat();

        //the position inside of the asterisk chunk
        for(k = 0; k < i; k ++)
        {
            tempArr[k + j] = "*";
        }

        log.innerHTML += tempArr.join(" ") + "<br>";
    }
}

JSFiddle 的jsfiddle

This seems to work well: 这似乎运作良好:

 str = "1234567" len = str.length; for(var stars = 1; stars < len - 1; stars++) { for(var pos = 1; pos < len - stars; pos++) { var s = str.substr(0, pos) + new Array(stars + 1).join("*") + str.substr(pos + stars); document.write(s + "<br>"); } } 

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

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