【问题标题】:Need Algorithm and implementation help - Compare 2 files [closed]需要算法和实现帮助 - 比较 2 个文件 [关闭]
【发布时间】:2012-10-14 09:56:37
【问题描述】:

我的项目目的:有 4 个文件。他们每个人都有不同的行数。每行由一个或几个单词组成。现在,对于这些文件中的每一个,我想计算其他文件的常用词最多。

  • 例如。 (',' 是一个新行\n)
  • 输入:
  • 文件 1 行:A、B、C、D
  • 文件 2 行:C、D、E、F
  • 文件 3 行:A、E、C、G
  • 文件 4 行:C、E、F、A

  • 输出:

  • 文件 1:最多常用词为 2,它们在文件中:文件 2 (C,D)、文件 3 (A,C) 和文件 4 (C,A)。
  • 文件 2:最多常用词为 3 个,它们在文件中:文件 4 (C,E,F)。
  • 文件 3:最多常用词为 3,它们在文件中:文件 4 (C,E,A)。
  • 文件 4:最多常用词为 3,它们在文件中:文件 2 (C,E,F)。

我的逻辑:

  1. 开始
  2. 从文件中读取每一行并将其作为一维数组存储在内存中(例如,array1[0] = "A"、array1[1] = "B" 等等。
  3. 由于有 4 个文件,我创建了 4 个数组 = array1 到 array4。它们中的每一个都将具有其相应文件的内容。
  4. 现在我将比较第一个数组中的第一个单词和第二个数组中的第一个单词。
  5. 现在我将比较第一个数组中的第一个单词和第二个数组中的第二个单词,依此类推,直到第二个数组结束。
  6. 我将继续这个直到最后一个数组中的最后一个单词。
  7. 当我发现匹配的内容时,我会通过递增 1 在变量中记下。

想知道这是否是解决这个问题的正确方法。

或者有没有更好的方法来思考这个问题?

编辑: 1.忘记添加了,会用php。

【问题讨论】:

  • 我会将找到的单词保存在一个数组中的文件中,如下所示:if(isset($found_words_of_file_a[$word])) { $found_words_of_file_a[$word]++; } else { $found_words_of_file_a[$word] = 1; }。如您所见,键是单词,值是单词在文件中的总次数。易于访问并易于与其他阵列进行比较。我不知道使用命名索引有什么性能问题..

标签: php algorithm implementation


【解决方案1】:

我从这样的有趣情况中学习了 PHP。继续学习。

// put all files in same directory as this script
// put file names in this array
$files = array('1.txt','2.txt','3.txt','4.txt');
$words = array();
$data = '';

$delimiter = "\n";  // change this to \r if running windows OS
// itterate through the files and create a word list  
foreach($files as $file){
    $fh = fopen($file,'r');
    $data .= $delimiter.fread($fh,filesize($file));
    fclose($fh);
}
// assuming 1 match per line like your question example 
$lines = explode($delimiter,$data);

foreach($lines as $line){
    $line = trim($line);
    if(empty($line)) continue;
    @$words[$line] += 1;  // @ suppreses notices
}

var_dump($words);
/* *
 * according to your example:
 *
array(7) {
  ["A"]=>
  int(3)
  ["B"]=>
  int(1)
  ["C"]=>
  int(4)
  ["D"]=>
  int(2)
  ["E"]=>
  int(3)
  ["F"]=>
  int(2)
  ["G"]=>
  int(1)
} 
*/

【讨论】:

  • 感谢您帮助我了解完整的逻辑 :-)
【解决方案2】:

使用array_intersect 应该可以轻松完成。

【讨论】:

  • 谢谢你告诉我一个直接的函数
  • 不客气,将它与count() 结合起来,您就已经完成了一半,代码非常简单,效果很好。 :)
【解决方案3】:

您应该首先对数组进行排序。然后,要计算array1array2 之间的公共线路数,有两个计数器i1i2

伪代码:

while(i1 < array.length && i2 < array2.length)
  if array1[i1] == array2[i2]
    ++i1; ++i2
    ++result
  else if array1[i1] < array2[i2]
    ++i1
  else
    ++i2

【讨论】:

  • 感谢您告诉它应该排序。我明白,从长远来看,这可能会节省时间
猜你喜欢
  • 2021-11-12
  • 1970-01-01
  • 2023-01-12
  • 1970-01-01
  • 2017-08-18
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多