问题:老师给学生分苹果,学生个数不定,年龄各不相同,要求老师根据学生年龄分苹果,相邻两个同学,年龄大的同学比年龄小的多分一个苹果,不允许给学生排序,请写出相应算法。
public class PersonNew {
int postion;//所在的位置
int age;//年龄
int apple;//分几个苹果
public PersonNew(int postion, int age, int apple) {
this.postion = postion;
this.age = age;
this.apple = apple;
}
public int getPostion() {
return postion;
}
public void setPostion(int postion) {
this.postion = postion;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public int getApple() {
return apple;
}
public void setApple(int apple) {
this.apple = apple;
}
@Override
public boolean equals(Object obj) {
if (obj instanceof PersonNew) {
PersonNew person = (PersonNew) obj;
if (person.age == this.age) {
return true;
} else {
return false;
}
} else {
return false;
}
}
}
public class Exc_1 {
public static int COUNT = 50;//测试数据条数,COUNT大于2
public static void main(String[] args) {
List data = new ArrayList();
Random random = new Random();
for (int i = 0; i < COUNT; ) {
int age = random.nextInt(100) + 1;
PersonNew pn = new PersonNew(i, age, 0);
if (!data.contains(pn)) {
data.add(pn);
i++;
}
}
//查看初始化数据后的结果
// showInfo(data);
boolean isBigger = true;//从第一个数和第二个数比较确定是正弦还是余弦
if (data.get(0).getAge() > data.get(1).getAge()) {
isBigger = true;
} else {
isBigger = false;
}
int step = 1;
for (int i = 1; i < COUNT - 1; i++) {
if (isBigger) {
if (data.get(i).getAge() > data.get(i + 1).getAge()) {
step = i;
} else {
break;
}
} else {
if (data.get(i).getAge() < data.get(i + 1).getAge()) {
step = i;
} else {
break;
}
}
}
//确定一点(封顶或谷底)的同学分到的苹果 设置为1
data.get(step).setApple(1);
for (int i = step; i >= 1; i--) {
if (data.get(i - 1).getAge() > data.get(i).getAge()) {
data.get(i - 1).setApple(data.get(i).getApple() + 1);
} else {
data.get(i - 1).setApple(data.get(i).getApple() - 1);
}
}
for (int i = step; i < COUNT - 1; i++) {
if (data.get(i + 1).getAge() > data.get(i).getAge()) {
data.get(i + 1).setApple(data.get(i).getApple() + 1);
} else {
data.get(i + 1).setApple(data.get(i).getApple() - 1);
}
}
//showInfo(data);
//找出最小的值
int minNum = data.get(0).getApple();
for (int i = 1; i < COUNT; i++) {
if (data.get(i).getApple() < minNum) {
minNum = data.get(i).getApple();
}
}
int addNum = 1 - minNum;
for (int i = 0; i < COUNT; i++) {
data.get(i).setApple(data.get(i).getApple() + addNum);
}
showInfo(data);
}
private static void showInfo(List data) {
StringBuffer sb = new StringBuffer();
for (int i = 0; i < data.size(); i++) {
sb.append("[" + data.get(i).getAge() + "," + data.get(i).getApple() + "]");
}
System.out.println(sb.toString());
System.out.println("数据是否符合条件:"+validData(data));
}
//验证数据是否符合条件
private static boolean validData(List data) {
boolean isValid = false;
for (int i = 0; i < data.size() - 1; i++) {
PersonNew pn1 = data.get(i);
PersonNew pn2 = data.get(i + 1);
if (Math.abs(pn1.getApple() - pn2.getApple()) == 1
&& pn1.getApple() > 0
&& pn2.getApple() > 0) {
isValid = true;
} else {
isValid = false;
break;
}
}
return isValid;
}
}