笔试题目1

实现 n 重循环的算法,n 是变量,且每重循环的循环次数也是变量。例如:

传入参数是 [1, 2],那么意味着外层循环数是 1,内层循环数数是 2。
如果传入参数是 [2, 2, 1],那么意味着最外层循环数是 2,次层循环数数是 2,最内层循环数是 1,依此类推。

要求打印出每一次循环的维度索引。

用 javascript 伪码表示为:

``` js
var dims = [2, 2]
loopGen = require('your-generator')(dims)
for indexes of loopGen
    console.log(indexes)
```

结果应该是:

```
[0, 0]
[0, 1]
[1, 0]
[1, 1]
```

类似地,如果输入是 `var dims = [2,2,2]`,那么结果是:

```
[ 0, 0, 0 ]
[ 0, 0, 1 ]
[ 0, 1, 0 ]
[ 0, 1, 1 ]
[ 1, 0, 0 ]
[ 1, 0, 1 ]
[ 1, 1, 0 ]
[ 1, 1, 1 ]
```

这段 javascript 伪代码用到了 `generator` 和 `for of` 语法,你在实现时不用考虑是否采用类似语法,只要确保能够根据传入的动态维度信息来执 

简单实现了下功能 

import com.alibaba.fastjson.JSONArray;

import java.util.Scanner;

/**
 * @author admin
 * @version v1.0
 * @description
 * @date 2020/1/9
 */
public class LoopGen {

    public static void main(String[] args) {

        String regex = "\\[(\\s*\\d\\s*,\\s*)*\\s*\\d\\s*]";
        while (true) {

            Scanner scanner = new Scanner(System.in);
            System.out.println("------------请输入字符串------- eg. [1,2]");
            //因为Scanner的next默认的匹配方式是遇到空格和换行符
            //String next = scanner.next();
            String next = scanner.nextLine();
            if (next == null || "".equals(next.trim()) || !Pattern.matches(regex, next)) {
                System.out.println("字符串输入异常,请重新输入.....");
                continue;
            }
            System.out.println("当前输入的字符串是:" + next);
            String arrayStr = next.replaceAll(" ", "");
            System.out.println("当前输入的字符串(去除空格)是:" + arrayStr);
            JSONArray array = JSONArray.parseArray(arrayStr);

            StringBuilder builder = new StringBuilder("[ ");
            println(array, builder, 0);
        }
    }

    private static void println(JSONArray array, StringBuilder builder, int index) {
        int key = array.getInteger(index);
        int indexTemp = index;
        StringBuilder builderTemp = new StringBuilder(builder.toString());
        for (int k = 0; k < key ; k++) {
            builder.append(k + ", ");
            if (++index < array.size()) {
                println(array, builder, index);
            } else {
                builder = new StringBuilder(builder.substring(0, builder.toString().lastIndexOf(",")));
                builder.append(" ]");
                System.out.println(builder.toString());
            }
            builder = new StringBuilder(builderTemp.toString());
            index = indexTemp;
        }
    }
}

 

测试结果:
------------请输入字符串------- eg. [1,2]
[2,2]
[ 0, 0 ]
[ 0, 1 ]
[ 1, 0 ]
[ 1, 1 ]
------------请输入字符串------- eg. [1,2]
[3,3,3]
[ 0, 0, 0 ]
[ 0, 0, 1 ]
[ 0, 0, 2 ]
[ 0, 1, 0 ]
[ 0, 1, 1 ]
[ 0, 1, 2 ]
[ 0, 2, 0 ]
[ 0, 2, 1 ]
[ 0, 2, 2 ]
[ 1, 0, 0 ]
[ 1, 0, 1 ]
[ 1, 0, 2 ]
[ 1, 1, 0 ]
[ 1, 1, 1 ]
[ 1, 1, 2 ]
[ 1, 2, 0 ]
[ 1, 2, 1 ]
[ 1, 2, 2 ]
[ 2, 0, 0 ]
[ 2, 0, 1 ]
[ 2, 0, 2 ]
[ 2, 1, 0 ]
[ 2, 1, 1 ]
[ 2, 1, 2 ]
[ 2, 2, 0 ]
[ 2, 2, 1 ]
[ 2, 2, 2 ]
------------请输入字符串------- eg. [1,2]

 

你可能感兴趣的:(java)