这个是自己写的算法,如果有大牛,麻烦帮我并行化。初学者则可以学到不少东西。

产生测试用例

import java.io.*;
import java.util.Random; public class ProduceCase { public static void main(String[] argvs){
File file2 = new File("D:\\YounG\\TestCases\\MySet\\test.txt");
FileWriter fw = null;
BufferedWriter writer = null;
try {
fw = new FileWriter(file2);
writer = new BufferedWriter(fw);
for(int i = 0; i < 500000; i++){
StringBuilder stringBuilder = new StringBuilder();
Random random = new Random();
for(int j = 0; j < random.nextInt(21); j++){
String s = getRandomString();
if(" ".equals(s)&&s.isEmpty()) continue;
stringBuilder.append(s + " ");
}
writer.write(stringBuilder.toString());
writer.newLine();//换行
}
writer.flush();
} catch (FileNotFoundException e) {
e.printStackTrace();
}catch (IOException e) {
e.printStackTrace();
}finally{
try {
writer.close();
fw.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
public static String getRandomString( ) { //length表示生成字符串的长度
Random random = new Random();
StringBuilder sb = new StringBuilder();
int length = random.nextInt(10);
for (int i = 0; i < length; i++) {
int number = random.nextInt(26);
sb.append(String.valueOf((char) (number+65) ));
}
return sb.toString();
}
}

  合并集合:

import java.io.*;
import java.util.*; public class MapTest {
public static void main(String[] argvs) {
File file = new File("D:\\YounG\\TestCases\\MySet\\test.txt");
BufferedReader reader = null;
List<HashSet> mySets = new ArrayList<>(500000);
boolean hasEmpty = false;
try {
reader = new BufferedReader(new FileReader(file));
String tempString;
// 一次读入一行,直到读入null为文件结束
while ((tempString = reader.readLine()) != null) {
// 显示行号
Scanner scanner = new Scanner(tempString);
HashSet<String> mySet = new HashSet<>();
mySet.clear();
while (scanner.hasNext()) {
mySet.add(scanner.next());
}
scanner.close();
//对个集合内部进行排序,定义大小。放弃排序。
if (mySet.isEmpty() && !hasEmpty) hasEmpty = true;
else
mySets.add(mySet);
}
reader.close();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (reader != null) {
try {
reader.close();
} catch (IOException e1) {
}
}
} List<Integer> destList = new ArrayList<>(mySets.size());
int setsSize = mySets.size();
for (int i = 0; i < setsSize; ++i) {
destList.add(i);
}
Map<String,Integer> mergeMap = new HashMap<>(1000000); //合并图。 long startTime=System.currentTimeMillis(); //获取开始时间 for (int setId = 0; setId < mySets.size(); ++setId) {
Iterator<String> iterator = mySets.get(setId).iterator();
List<String> setElem = new ArrayList<>(50);//先把元素全部迭代出来,避免了多线程错误。
while (iterator.hasNext())
setElem.add(iterator.next());
int elemNumOfSet = setElem.size();
for(int j = 0; j < elemNumOfSet; j++) {
if( mergeMap.containsKey( setElem.get(j) ) ) { //判断当前元素是否包含在合并记录表里边。永远不要用直接下标访问(伪下标)
Integer destValueSetId = destList.get( mergeMap.get( setElem.get(j) ).intValue() ); //真实 的包含该元素的最小集合号。
Integer destLoopSetId = destList.get(setId);
if( destValueSetId.compareTo( destLoopSetId ) > 0 ) {
// Iterator putIterator = mySets.get(destValue).iterator();
// while (putIterator.hasNext())
// mergeMap.put((String) putIterator.next(), destList.get(setId)); //找过的元素记得入mergeMap。
mySets.get( destLoopSetId ).addAll( mySets.get(destValueSetId) );//Set中元素增多,所以iterator失效,故重新复制。且Hash 存储本身就是无序的,随着元素的增加是会改动存储顺序的。
//推测,HashSet与HashMap不同HashSet不过就是所有的Value是一个固定的地址罢了。而HashMap分为了Value和Key两个集合。
mySets.get( destValueSetId ).clear();
for (int i = 0; i < destList.size(); i++) {
if ( destList.get(i).equals( destValueSetId ) ) {
destList.set(i, destLoopSetId );
}
}
}
else if(destValueSetId.compareTo( destLoopSetId ) < 0) {
// Iterator putIterator = mySets.get(destValue).iterator();
// while (putIterator.hasNext())
// mergeMap.put((String) putIterator.next(), destValue); //找过的元素记得入mergeMap。
mySets.get( destValueSetId ).addAll( mySets.get(destLoopSetId));
mySets.get( destLoopSetId ).clear();
for (int i = 0; i < destList.size(); i++) {
if ( destList.get(i).equals( destLoopSetId )) {
destList.set(i, destValueSetId);
}
}
}
}
else {
mergeMap.put( setElem.get(j) , setId ); //此处切记不可用destList.get(iSet),因为该值并不稳定。
}
}
} long endTime=System.currentTimeMillis(); //获取结束时间
System.out.println("程序运行时间: "+(endTime-startTime)+"ms"); Iterator iterator = mySets.iterator();
File file2 = new File("D:\\YounG\\TestCases\\MySet\\testACK.txt");
FileWriter fw = null;
BufferedWriter writer = null;
try {
fw = new FileWriter(file2);
writer = new BufferedWriter(fw);
while(iterator.hasNext()){
HashSet<String> temp = (HashSet<String>) iterator.next();
if(!temp.isEmpty()) {
writer.write( temp.toString() );
writer.newLine();
}
}
writer.flush();
} catch (FileNotFoundException e) {
e.printStackTrace();
}catch (IOException e) {
e.printStackTrace();
}finally{
try {
writer.close();
fw.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}

验证输出结果:

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.util.*;
import java.util.regex.Pattern; /**
* Created by Young on 2015/12/25.
* 如何测试测试用例:
* 1.所有的元素不重复,/hashSet
* 2.元素的种类不减少,/count
* 3.没有非法合并。(非法合并指,合并过程中,不存在共同元素依然合并),这一项适合在合并程序必然实现。
* 3 must be true since contains and addAll execute as the same time.
*/
public class Validaty {
public static void main(String[] args) {
File file = new File("D:\\YounG\\TestCases\\MySet\\testACK.txt");
BufferedReader reader = null;
Set allSet = new HashSet<String>();
//int count1 = 0;
try {
reader = new BufferedReader(new FileReader(file));
String tempString;
// 一次读入一行,直到读入null为文件结束
allSet.clear();
while ((tempString = reader.readLine()) != null) {
// 显示行号
tempString = tempString.substring(1,tempString.length()-1);
//Pattern pattern = Pattern.compile(",");
String[] strings = tempString.split(", ");
int strj = 0;
while (strj < strings.length && !strings[strj].isEmpty()){
if (allSet.contains(strings[strj])) {
System.out.println("Wrong ACK for \"" + strings[strj] + "\" is repeated");
return;
}
allSet.add(strings[strj]);
strj++;
}
/* Scanner scanner = new Scanner(tempString);
while (scanner.hasNext()) {
String temp = scanner.next();
if (allSet.contains(temp)) {
System.out.println("Wrong ACK for " + temp + "is repeated");
return;
}
allSet.add(temp);
//++count1;
}
scanner.close();*/
}
reader.close();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (reader != null) {
try {
reader.close();
} catch (IOException e1) {
}
}
} File file2 = new File("D:\\YounG\\TestCases\\MySet\\test.txt");
BufferedReader reader2 = null;
try {
reader2 = new BufferedReader(new FileReader(file2));
String tempString;
// 一次读入一行,直到读入null为文件结束 while ((tempString = reader2.readLine()) != null) {
// 显示行号
Scanner scanner = new Scanner(tempString);
while (scanner.hasNext()) {
String temp = scanner.next();
if (!allSet.contains(temp)) {
System.out.println("Wrong ACK for lost elem " + temp);
return;
}
}
scanner.close();
}
reader2.close();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (reader != null) {
try {
reader.close();
} catch (IOException e1) {
}
}
} System.out.println("Right ACK");
}
}

最完整的合并相交集合的Java代码(查并集)的更多相关文章

  1. JAVA 代码查错

    1.abstract class Name { private String name; public abstract boolean isStupidName(String name){}} 大侠 ...

  2. Java代码查错部分?

    1. abstract class Name { private String name; public abstract boolean isStupidName(String name) {} } ...

  3. java代码中后台向前台传递list或map集合案例

    导入jar包 新建一个servert传递map集合 ajax.java代码: package servlet; import java.io.IOException; import java.io.P ...

  4. Android开发:《Gradle Recipes for Android》阅读笔记(翻译)3.5——在flavors间合并java代码

    问题: 你想要在单独的product flavors里面增加Acitivity或者其它java类. 解决方案: 创建合适的代码目录,增加java类,将它们和main代码合并. 讨论: flavors和 ...

  5. 关于Hash集合以及Java中的内存泄漏

    <学习笔记>关于Hash集合以及Java中的内存泄漏 标签: 学习笔记内存泄露hash 2015-10-11 21:26 58人阅读 评论(0) 收藏 举报  分类: 学习笔记(5)  版 ...

  6. java集合系列——java集合概述(一)

    在JDK中集合是很重要的,学习java那么一定要好好的去了解一下集合的源码以及一些集合实现的思想! 一:集合的UML类图(网上下载的图片) Java集合工具包位置是java.util.* 二:集合工具 ...

  7. c++ 集合的增删改查,与两集合的合并 缺陷(空间大小不灵活)

    #if 1 #include <iostream> #include <stdlib.h> using namespace std; class List { public: ...

  8. scala集合与java集合的转换应用

    今天在业务开发中遇到需要Scala集合转为Java集合的场景: 因为业务全部是由Scala开发,但是也避免不了调用Java方法的场景,所以将此记录下来加深记忆: import scala.collec ...

  9. C# Net 合并int集合为字符串,如:输入1,2,3,4,8 输出1~4,8

    C# Net 合并int集合为字符串,如:输入1,2,3,4,8 输出1~4,8 粘贴代码使用: /// <summary> /// 合并int集合,如1,2,3,4,8 输出1~4,8 ...

随机推荐

  1. CentOS 6.7安装配置Cacti监控系统

    一.安装配置LAMP环境 yum -y install httpd php php-mysql php-snmp php-xml php-gd mysql mysql-server 启动http和my ...

  2. JavaScript的DOM操作(二)

    一:window.history对象 历史记录,通过历史记录可以操作页面前进或者后退 window.history.back();后退 window.history.forward();前进 wind ...

  3. C#中的static静态变量的用法

    静态全局变量 定义:在全局变量前,加上关键字 static 该变量就被定义成为了一个静态全局变量. 特点: A.该变量在全局数据区分配内存. B.初始化:如果不显式初始化,那么将被隐式初始化为0. 静 ...

  4. IE的@cc_on条件编译

    1: alert("浏览器版本为:"+sSuffix) 用来判断浏览器的版本很好用 var b = /*@cc_on!@*/false; 其中/*@cc_on ..... @*/之 ...

  5. MyXLS案例

    using System; using System.Data; using org.in2bits.MyXls; namespace Maticsoft.Common { /// <summa ...

  6. [Session] SessionHelper---C#操作Session的帮助类 (转载)

    点击下载 SessionHelper.rar 下面是代码大家看一下 这个类主要是关于Session的基本操作比如:1.获取Session值2.设置一个Session的值3.清空所有的Session4. ...

  7. OC - 17.AFNetworking原理及常用操作

    AFN的六大模块 NSURLConnection,主要对NSURLConnection进行了进一步的封装,包含以下核心的类: AFURLConnectionOperation AFHTTPReques ...

  8. javascript入门学习笔记2

    JavaScript 拥有动态类型.这意味着相同的变量可用作不同的类型: 实例 var x // x 为 undefined var x = 6; // x 为数字 var x = "Bil ...

  9. 数据库(学习整理)----5--Oracle常用的组函数

    其他: 1.oracle中下标是从1开始的,Java下标是从0开始的 函数分类: 日期函数 字符函数 转换函数 数学函数 系统函数 ---在当前月份上面:增加.减少月份 select add_mont ...

  10. java 反射取得方法入参类型的泛形

    package TestReflectClass; import java.util.List; /** * Created by wangyang on 2016/12/16. */ public ...