java,
分享于 点击 18351 次 点评:277
java,
输入:N(整数)输入:数据文件A.txt,不超过6条记录,字符串长度不超过15个字节
文件格式如下:
字符串\t数字\n
说明:
每行为1条记录;字符串中不含有\t。
数字描述的是该字符串的出现概率,小于等于100的整数。
多条记录的出现概率之和为100,如果A.txt不满足该条件,程序则退出;
如果文件格式错误,程序也退出。
要求:
编写一个程序,输入为N(正整数),读入文件A.txt,按照字符串出现概率随机地输出字符串,输出N条记录
例如:
输入文件A.txt
abc\t20
a\t30
de\t50
输入为:10
即 abc有20%的概率输出,a有30%的概率输出,de有50%的概率输出,输出10条记录
以下为一次输出的结果,多次输出的结果可能不相同。
abc
a
de
de
abc
de
a
de
a
de
import java.util.Random;
import java.util.Vector;
public class Rand {
private int num = 10;
class Node {
public String k;
public int v;
public int count = 0;
public Node(String _k, int _v) {
this.k = _k;
this.v = _v;
this.count = v * num / 100;
}
}
public static void main(String[] args) {
Vector<Node> vector = new Vector<Node>();
Rand rand = new Rand();
rand.num = 10;
vector.add(rand.new Node("abc", 20));
vector.add(rand.new Node("a", 30));
vector.add(rand.new Node("de", 50));
Random random = new Random();
while (!vector.isEmpty()) {
int i = vector.size();
int index = random.nextInt(i);
if (index == vector.size())
index--;
Node item = vector.get(index);
System.out.println(item.k);
item.count--;
if (item.count == 0)
vector.remove(index);
}
}
}
相关文章
- 暂无相关文章
用户点评