今天一个面试官老大哥,让我用springboot实现一个前后端交互的小例子,要求前端输入一个二维数组,提交后返回的数据 顺时针 打印出来,前后端交互问题是不大,主要是顺时针打印如图:
顺时针打印的意思如下图:
要求的结果如下图:
结果搞半天弄不出来,后来面试结束,我不死心,最后用笨方法来解决了;
这里请教各位有什么好的办法来解决吗?
(下面粘贴我的代码)
Title
package com.example.demo2.controller;
import com.example.demo2.InfoDto;
import com.example.demo2.common.Result;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import java.util.ArrayList;
import java.util.List;
@RestController
public class LoginController {
@PostMapping("login")
@ResponseBody
public Result login(InfoDto dto){
Result result = new Result<>();
StringBuilder sb = new StringBuilder();
sb.append("账号:").append(dto.getAccount()).append("
");
sb.append("密码:").append(dto.getPassword()).append("
");
//获取二维数组
String[][] arrays = getParams(dto.getDesc().trim());
//获取最小边
int min = getMin(arrays);
List res = new ArrayList<>();
int x = 0, y = 0;
for(int i=0; i< min; i++){
//更新起点
x=y=i;
//System.out.println(printLine(i,i,arrays));
res.addAll(printLine(i,i,arrays));
//更新起点
x=1+i;
y=arrays[0].length - 1 - i;
//System.out.println(printCol(x ,y,arrays));
res.addAll(printCol(x ,y,arrays));
//更新起点
x=(arrays.length - 1) - i;
y=(arrays[0].length - 1) -1 - i;
//System.out.println(_printLine(x ,y,arrays));
res.addAll(_printLine(x,y,arrays));
//更新起点
x=(arrays.length - 1) - 1 - i;
y= i;
//System.out.println(_printCol(x ,y,arrays));
res.addAll(_printCol(x,y,arrays));
}
System.out.println(res.toString());
result.setCode(200);
result.setMsg("成功");
sb.append("顺时针转:").append("
");
sb.append(res);
result.setContent(sb.toString());
return result;
}
// 横向从做到又
private List printLine(Integer x, Integer y, String[][] arrays){
List list = new ArrayList<>();
int current = x;
for(int i=x; i printCol(Integer x, Integer y, String[][] arrays){
List list = new ArrayList<>();
int current = x - 1;
for(int i=x; i _printLine(int x, int y, String[][] arrays){
List list = new ArrayList<>();
int maxIndex = (arrays.length - 1);
int current = maxIndex - x;
for (int i = y; i >= 0 + current; i--) {
list.add(arrays[x][i].trim());
}
return list;
}
// 竖向从下到上
private static List _printCol(int x, int y, String[][] arrays){
List list = new ArrayList<>();
int current = y;
for (int i = x; i >= 0 + (current+1); i--) {
list.add(arrays[i][y].trim());
}
return list;
}
// 截取字符串, 获取二维数组
private String [][] getParams(String source){
String [][] resArray = {};
String[] firstArray = source.split(";");
for (int i=0; i
最后打印的效果如下: