【发布时间】:2015-08-21 17:05:17
【问题描述】:
问题描述:-
我有两个文件。每个文件都有 order_number,这是一个随机的字母数字字符串,它们彼此唯一。 两个文件都包含相同数量的 order_number,如果一个 order_number 在一个文件中,则无论它在文件中的位置如何,它都必须存在于另一个文件中。
下面是苍蝇的例子:
-
文件1
abc123 def234 skd109 djkk09 nknk323 -
文件2
skd109 def234 abc123 nknk323 djkk09
现在我要编写一个以file1为参考的程序,看看哪些订单根据file2中的位置相对翻转。
例如考虑以上两个文件。 file1 中的 order_number abc123 位于位置 1,但在 file2 中位于位置 3,并且分别位于 file2 中的两个 order_number ( skd109 和 def234 )之后。
Order_number def234 在 file2 中的 skd109 之后。
并且order_number djkk09 和nknk323 被翻转。
我的程序的输出应该是这样的:
abc123 is flipped by 2 ( +ve sign because it came after )
def234 is flipped by 0
skd109 is flipped by -2 ( -ve sign because it came before )
djkk09 is flipped by 1
nknk323 is flipped by -1
注意:每个文件中都有超过百万条记录。所以解决方案应该是有效的。
下面是我的代码:-
import java.util.*;
import java.io.*;
public class Matching {
public static void main( String args[]) throws IOException{
/* Variable Declaration */
int ordersFlipped = 0;
int ordersNotFlipped = 0;
String lineFile1 = null;
String lineFile2 = null;
int indexFile2 = 0;
int indexFile1 = 0;
/* Scanner */
BufferedReader file2 = new BufferedReader(new FileReader("FlipAnalysis/file2"));
BufferedReader file1 = new BufferedReader(new FileReader("file1"));
/* File Creation */
File file = new File("Result");
/* Objects to write into the files */
PrintWriter outputResult = new PrintWriter(file);
/* Hash Map*/
Map<String,Integer> map = new HashMap<String, Integer>();
while ((lineFile2 = file2.readLine()) != null){
indexFile2++;
map.put(line,indexMe);
}
System.out.println("Map is ready. Now performing Matching.");
while (( lineFile1 = inputFile1.readLine()) != null){
indexFile1++;
if(map.containsKey(lineFile1)){
if(((indexFile - map.get(lineFile1))!= 0)
{
outputResult.println(lineFile1 + " Flipped by: " +(indexFile - map.get(lineFile1));
orderFlipped++;
}
else{
outputResult.println( lineFile1 + " Flipped by: 0" );
ordersNotFlipped++;
}
}
}
outputResult.println("\n\n--------------------------------------------------------------\n"+ "Total Order Flipped: " +ordersFlipped);
outputResult.println("\nOrder Not Flipped: " +ordersNotFlipped);
outputResult.println("\nTotal Number of Orders: " + (ordersFlipped + ordersNotFlipped));
System.out.println("Done!!");
inputFile2.close();
inputFile1.close();
outputResult.close();
}
}
【问题讨论】:
-
这不是一个外包你的家庭作业或工作任务的网站。付出一些努力,如果您需要具体的帮助,请提出问题。
-
我确实付出了一些努力。以下是我的逻辑:- 1. 创建 HashMap 来存储 file2。 Map
map = new HashMap (); while ((lineMe = inputMe.readLine()) != null){ indexMe++; map.put(lineMe,intexMe++); 2. 逐行读取file1。并比较索引号以获得翻转。 while (( lineOuch = inputOuch.readLine()) != null){ } -
@OP,很高兴听到。现在您可以使用该代码编辑您的原始帖子,使其更具可读性,并让其他人看到它。这样你会得到更好的帮助。
-
不应输出为:
abc123 is flipped by 2、def234 is flipped by 0、skd109 is flipped by -2、djkk09 is flipped by 1、nknk323 is flipped by -1?如果不是,我不明白你的逻辑。 -
是的,你是对的...!!
标签: java algorithm performance list hashmap