2017-01-25 26 views
0

比較兩個文件,我在.dimacs格式的兩個文件,如:在他們的線路內容斯卡拉

c example_01.cnf 
p cnf 6 9 
    1 0 
-2 1 0 
-1 2 0 
-5 1 0 
-6 1 0 
-3 2 0 
-4 2 0 
-3 -4 0 
    3 4 -2 0 

,並

c example_02.cnf 
p cnf 9 6 
-7 2 0 
7 -2 0 
-8 3 0 
8 -3 0 
-9 4 0 
9 -4 0 

我想比較的文件example_01.cnfexample_02.cnf這樣,以提取只有那些來自文件example_01.cnf的行與文件具有相似的值(在任何行中),並將結果保存在新文件中,例如example_result.cnf

在這種情況下,example_result.cnf看起來像:

c example_result.cnf 
p cnf 4 6 
-2 1 0 
-1 2 0 
-3 2 0 
-4 2 0 
-3 -4 0 
3 4 -2 0 

例如,線1 0-5 1 0-6 1 0不是生成的文件中,因爲沒有數字156example_02.cnf

我當前的代碼是:

import scala.io.Source 

    object Example_01 { 

     val source = Source.fromFile("example_01.cnf") 
     val source2 = Source.fromFile("example_02.cnf") 
     val destination = new PrintWriter(new File("example_result.cnf")) 

     def main(args: Array[String]): Unit = { 

     var nrVariables: Int = 0 
     var nrLines: Int = 0 

     destination.write("c example_result.cnf \n") 
     destination.write("p cnf " + nrVariables + " " + nrLines + "\n") //not finished! 

     /* How I can compare the all the numbers from the second file 'source2' like in the 'if' statement below? */    
     for(line <- source.getLines()) ; if line.contains("2") & line.contains("0")) { 
      destination.write(line) 
      destination.write("\n") 
      nrLines += 1   
     } 
     source.close() 
     destination.close() 
     } 

在這段代碼中,我不使用第二個文件example_02.cnf呢。我如何比較這兩個文件?

回答

0

好吧,如果你想保存線形成含有源2的任何行中的數字來源1這應該工作:

object Example { 
    val source = Source.fromFile("example_01.cnf").getLines() 
    val source2 = Source.fromFile("example_02.cnf").getLines() 
    val nrsSource2 = source2.mkString(" ").split(" ").distinct.diff(Array("0")) 

    val linesToSave = source.drop(2).filter { 
    l => 
     l.split(" ").exists(nr => nrsSource2.contains(nr)) 
    } 

    val nrLines = linesToSave.length 
    val nrVariables = ??? //don't know what this is 

    //write linesToSave to a file 
} 

不確定nrVariables代表什麼,但應該很容易從linesToSave計算。

+0

我正在嘗試使用這種過濾方法,我不知道爲什麼我再次獲得相同的文件1.它看起來像存在(nr => nrsSource2.contains(nr))'總是成爲真正的! :(順便說一句,我檢查了什麼'nrsSource2'包含,它看起來一切都很好。你有任何線索,爲什麼? – user4712458

+0

@ user4712458我認爲這是forAll而不存在檢查我更新的答案 – nmat

+0

方法'forall )似乎可以解決一個問題:當在'source'中找不到來自'nrSource2'的數字時,那麼它將在這些行中刪除/(不檢查):/它在檢查來自'nrSource2的其他值之前刪除行'。 – user4712458

0

概念上,它應該是水木清華類似以下內容:

val file1: List[String] = // read file and getLines 
val file2: List[String] = // read file and getLines 

val result = file1.filter { line => 
    file2.contains(line) 
}