版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/ARPOSPF/article/details/82414008
画心形
题目描述:
你需要在一个10*10的点阵中,根据制定的两个顶点,画出一个符合要求的心形,如下如:
输入描述:
你会得到两组参数,代表这心形上端两个点的坐标,(x1,y1),(x2,y2)代表这两点所在的行列,如上图,你得到的坐标为(2,3),(2,7)
数据保证 x2=x1,|y1-y2| >1
输入格式为:
2 3 2 7
输出描述:
你需要输出一个10*10的点阵
需要画心形的部分为‘#’,不需要画的部分为‘-’,每两个点之间用空格分开,结果没有空格
参考样例,心形由三个等腰直角三角形组成
心形边缘斜线的斜率为±1,关于奇偶的处理参考输入输出样例
心形可能会超出边界,超出部分不需要画出。
解法:
根据输入的两个点的坐标可以计算出上端等腰三角形和下端等腰三角形的高度,
- 如果行数i小于心形的上顶点行号或者大于心形的下顶点行号,则全部打印‘-’;
- 将剩余区域分为上下两部分,以行号是否超过上端等腰三角形底边为界:
- 在上端,两个等腰三角形将区域划分为三个部分,分为左部分,中间部分、右部分,根据顶点坐标计算出每个部分的边界位点,然后打印相应字符即可
- 同样,在下端,一个大的等腰三角形将区域划分为两部分,分别为左部分、右部分。此时需要注意的是,如果|y1-y2|为偶数,则下端等腰三角形的底端顶点为1个点,否则为2个点。
代码:
import java.util.Scanner;
/**
* 携程笔试题1:画出心型
* 输入两组参数,代表心型上端两个点的坐标,(x1,y1),(x2,y2)代表这两点所在的行列。
* 例如,2 3 2 7
* 代表坐标为(2,3),(2,7)的两个点
* 数据保证 x2=x1,|y1-y2|>1
*/
public class XieCheng_Code01 {
public static int smallHigh, bigHigh, bottomX, bottomY1, bottomY2;
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
while (sc.hasNext()) {
int x1 = sc.nextInt();
int y1 = sc.nextInt();
int x2 = sc.nextInt();
int y2 = sc.nextInt();
if (x1!=x2||Math.abs(y1-y2)<=1){
break;
}
smallHigh = (y2 - y1) / 2 + 1;//小三角形的高度
bigHigh = (y2 - y1) / 2 + (y2 - y1) / 2 + 1;//smallHigh;//大三角形的高度
//大三角形底部顶点的x坐标
if ((y2 - y1) / 2 % 2 == 0) {
bottomX = x1 + smallHigh - 1 + bigHigh - 1;
} else {
bottomX = x1 + smallHigh + bigHigh - 1;
}
if (y1 + (y2 - y1) / 2 == y2 - (y2 - y1) / 2) {
bottomY1 = bottomY2 = y1 + (y2 - y1) / 2;
} else {
bottomY1 = y1 + (y2 - y1) / 2;
bottomY2 = y2 - (y2 - y1) / 2;
}
solution(x1, y1, x2, y2);
}
sc.close();
}
private static void solution(int x1, int y1, int x2, int y2) {
for (int i = 1; i <= 10; i++) {
if (i < x1 || i > bottomX) {
for (int j = 1; j <= 10; j++) {
printSignal(j, "-");
}
} else {
processCore(i, x1, y1, x2, y2);
}
System.out.println();
}
}
private static void processCore(int i, int x1, int y1, int x2, int y2) {
if (i <= x1 + (y2 - y1) / 2) {
for (int j = 1; j <= 10; j++) {
if ((j >= 1 && j <= y1 + x1 - i - 1) ||
(j >= y1 - x1 + i + 1 && j <= y2 + x2 - i - 1) ||
(j >= y2 - x2 + i + 1 && j <= 10)) {
printSignal(j, "-");
} else {
printSignal(j, "*");
}
}
} else {
for (int j = 1; j <= 10; j++) {
if ((j >= 1 && j <= bottomY1 - (bottomX - i) - 1) ||
(j >= bottomY2 + (bottomX - i) + 1 && j <= 10)) {
printSignal(j, "-");
} else {
printSignal(j, "*");
}
}
}
}
private static void printSignal(int j, String c) {
if (j == 10) {
System.out.print(c);
} else {
System.out.print(c + " ");
}
}
}
测试结果: