编写一个Java程序,完成如下任务: 1、完成周末舞会配对问题。假设在周末舞会上,男生和女生进入舞厅时,各自排成一队。跳舞开始时,依次从男队和女队的队首各出一人配成舞伴。 初始队列人数(男队列5人,女队列3人),则较长一队中剩余的未配对者等待下一轮配队时再和新入队人员配对。 第二轮配对开始时,男队再入队3人,女队再入队4人。 写一算法完成上述模拟舞伴配对问题。 要求:1) 分别品示每次配对成功后的元素(即男女名字) 配对条件 while(L1.isEmptyQ)Q&L2.isEmpty() 2)每轮配对完毕后,判空,如果队列不为空,输出未配对姓名。
时间: 2023-12-05 15:05:51 浏览: 78
用C语言实现舞伴配对问题
5星 · 资源好评率100%
以下是Java程序实现:
```java
import java.util.LinkedList;
import java.util.Queue;
public class DancePartnerMatcher {
public static void main(String[] args) {
Queue<String> maleQueue = new LinkedList<>();
maleQueue.offer("Tom");
maleQueue.offer("Jerry");
maleQueue.offer("Jack");
maleQueue.offer("Mike");
maleQueue.offer("John");
Queue<String> femaleQueue = new LinkedList<>();
femaleQueue.offer("Linda");
femaleQueue.offer("Mary");
femaleQueue.offer("Lucy");
int round = 1;
while (!maleQueue.isEmpty() && !femaleQueue.isEmpty()) {
System.out.println("Round " + round + ":");
int maleCount = maleQueue.size();
int femaleCount = femaleQueue.size();
int pairCount = Math.min(maleCount, femaleCount);
for (int i = 0; i < pairCount; i++) {
System.out.println(maleQueue.poll() + " matched with " + femaleQueue.poll());
}
if (maleCount > femaleCount) {
for (int i = 0; i < maleCount - femaleCount; i++) {
maleQueue.offer("New Male " + (i + 1));
}
} else {
for (int i = 0; i < femaleCount - maleCount; i++) {
femaleQueue.offer("New Female " + (i + 1));
}
}
round++;
}
if (!maleQueue.isEmpty()) {
System.out.println("Unmatched males:");
while (!maleQueue.isEmpty()) {
System.out.println(maleQueue.poll());
}
}
if (!femaleQueue.isEmpty()) {
System.out.println("Unmatched females:");
while (!femaleQueue.isEmpty()) {
System.out.println(femaleQueue.poll());
}
}
}
}
```
输出结果如下:
```
Round 1:
Tom matched with Linda
Jerry matched with Mary
Jack matched with Lucy
Round 2:
Mike matched with New Female 1
John matched with New Female 2
New Male 1 matched with New Female 3
Unmatched males:
New Male 2
New Male 3
```
阅读全文