两行数据找相同元素
我有一个比如叫做input.txt 文本 格式如下
12 Follower[13,14,16,]
12 Following[14,29,39,]
13 Following[12,]
14 Follower[12,48,98,]
14 Following [12,48,90,]
这个文本是按照第一列的数字(之后成为用户) 升序排列的
我想找的是 比如用户12 他既有follower 也有following 我想找方括号里面相同的元素 并输出存为output.txt 例如:
12 [14]
14 [12,48]
应该怎么做??
请给我具体的code 谢谢 80分哟~~~
------解决方案--------------------
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.util.ArrayList;
public class FindSameNumber
{
void StringInArray(ArrayList<Integer> list, String str)
{
int start = 1;
int end = 0;
int i;
while (!str.substring(start).equals("]"))
{
for (i = start; i < str.length(); i++)
{
if (str.charAt(i) == ',')
{
end = i;
break;
}
}
int number = Integer.parseInt(str.substring(start, end));
list.add(number);
start = end + 1;
}
}
void find() throws Exception
{
BufferedReader br = new BufferedReader(new FileReader(new File(
"input.txt")));
BufferedWriter bw = new BufferedWriter(new FileWriter(new File(
"output.txt")));
String t1 = br.readLine();
String t2;
ArrayList<Integer> list1 = new ArrayList<Integer>();
ArrayList<Integer> list2 = new ArrayList<Integer>();
while (t1 != null)
{
t2 = br.readLine();
int user1Index = t1.indexOf(" F");
int user2Index = t2.indexOf(" F");
int number1 = Integer.parseInt(t1.substring(0, user1Index));
int number2 = Integer.parseInt(t2.substring(0, user2Index));
if (number1 == number2)
{
bw.write(number1 + " [");
int user1ArrayIndex = t1.indexOf("[");
int user2ArrayIndex = t2.indexOf("[");
StringInArray(list1, t1.substring(user1ArrayIndex));
StringInArray(list2, t2.substring(user2ArrayIndex));
int i = 0;
int j = 0;
while(i != list1.size() -1 && j != list2.size())
{
int ele1 = list1.get(i);
int ele2 = list2.get(j);
if(ele1 == ele2)
{
bw.write(ele1+",");
System.out.println(number1+":"+ele1);
i++;
j++;
}else
{
if(ele1 > ele2)
{
j++;
}else
{
i++;
}
}
}
bw.write("]\r\n");
t1 = br.readLine();
} else
{
t1 = t2;
}
}
br.close();
bw.close();
}
public static void main(String[] args) throws Exception
{
FindSameNumber fsm = new FindSameNumber();
fsm.find();
}
}
条件:
1.如果相同用户后不是Following就是Follower
2.用户的数组已经排好序
------解决方案--------------------
看看这个
http://topic.csdn.net/u/20120624/21/9357067a-552c-4200-a16c-f0924f4b2da6.html