给定一亿的QQ号,找出其中的情侣号对。其中情侣号的设置是这样的:相应位置的数字0-0,1-9,2-8……两个数字的和为10。
实现思路:
1、首先随机给出一亿个QQ号
2、读取这一亿个QQ号,将QQ压入map中
3、取出一个QQ号,计算与它匹配的情侣号。
4、在map中查找是否有这个情侣号。如果有将二者压入到另一个map里,否则返回3。
5、压入另一个map里的目的是避免重复输出同样的情侣号对。
随机生成一亿个QQ号的代码:
package Tencent;
import java.io.*;
import java.math.*;
import java.util.*;
public class couple {
public static String validateCode(int code_len) {
int count = 0;
char str[] = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9' };
StringBuffer pwd = new StringBuffer("");
Random r = new Random();
while (count < code_len) {
int i = Math.abs(r.nextInt(10));
if (i >= 0 && i < str.length) {
pwd.append(str[i]);
count++;
}
}
return pwd.toString();
}
public static void main(String args[])
{
//int random=(int)(Math.random()*1000000);
try{
OutputStreamWriter writer = new OutputStreamWriter(new FileOutputStream("qq.txt"));
couple cou = new couple();
String random;
for(int i=1; i <= 1000000000;i++)
{
random = cou.validateCode(9);
writer.write(random + "\n");
// System.out.println(random);
}
writer.flush();
writer.close();
}catch(IOException e)
{
e.printStackTrace();
}
}
}
找出情侣号对,并输出的代码:
package Tencent;
import java.io.*;
import java.util.*;
public class couple_map {
public static void main(String args[])
{
try{
FileReader fr = new FileReader("qq.txt");
BufferedReader reader = new BufferedReader(fr);
Map<String,Integer> map = new HashMap<String,Integer>();
Map<String,String> map1 = new HashMap<String,String>();
BufferedWriter writer = new BufferedWriter(new FileWriter("couple.txt"));
String qq;
String couple = "";
char num[] = new char[9];
while((qq = reader.readLine()) != null)
{
map.put(qq, 0);
}
Set<String> key = map.keySet();
for(Iterator<String> it = key.iterator();it.hasNext();)
{
String s = it.next();
num = s.toCharArray();
for(int j = 0;j <num.length;j++)
{
int count = num[j]-'0';
if(count == 0)
count = 0;
else
count = 10 - count;
String str = String.valueOf(count);
couple = couple + str;
}
if(map.containsKey(couple))
{
if(map1.containsValue(couple) != true)
map1.put(s, couple);
}
couple = "";
}
Set<String> key1 = map1.keySet();
for(Iterator<String> it = key1.iterator();it.hasNext();)
{
String s = it.next();
writer.write(s + " " + map1.get(s) +"\n");
}
reader.close();
writer.flush();
writer.close();
}catch(IOException e)
{
e.printStackTrace();
}
}
}