2016-03-13 42 views
0

我試圖弄清楚爲什麼這樣會在每個週期中打印「多數元素」候選者。多數元素未能結束週期

我一直在努力工作的代碼是多數元素搜索(找到一個元素重複超過列表長度的一半)。

我無法分離找到候選者和測試數組的過程,因爲我的輸入是具有不確定數量數組的文本文件。這是來自rosalind.info的練習,每次嘗試解決時都有不同的輸入。

輸入的一個例子是

-5 5 5 5 5 5 5 5 -8 7 7 7 1 7 3 7 -7 1 6 5 10 100 1000 1 -5 1 6 7 1 1 10 1 

這是我到目前爲止已經寫的。

foreach my $currentrow (@lists) { 

    my @row =(); 
    @row = split(/\s/, $currentrow); 

    my $length = $#row; 
    my $count = 0; 
    my $i  = 0; 

    for $i (0 .. $length - 1) { 

     if ($count == 0) { 
      $candidate = $row[$i]; 
      $count++; 
     } 

     if (($count > 0) and ($i = $length - 1)) { 

      my $counter2 = 0; 

      for my $j (0 .. $length - 1) { 
       if ($row[$j] == $candidate) { 
        $counter2++; 
       } 
      } 

      if ($counter2 <= ($#row/2) and ($i = $length - 1)) { 
       $candidate = -1; 
       print $candidate, " ", $i, " "; 
      } 

      if ($counter2 > ($#row/2) and ($i = $length - 1)) { 
       print $candidate, " ", $i, " "; 
      } 

     } 

     if ($candidate == $row[$i] and $count > 0) { 
      $count = $count + 1; 
     } 

     if ($candidate != $row[$i] and $count > 0) { 
      $count = $count - 1; 
     } 
    } 
} 
+0

顯示一些樣品輸入,預期的輸出和實際輸出 –

+0

-5 5 5 5 5 5 5 5 -8 7 7 7 1 7 3 7 -7 1 6 5 10 100 1000 1 -5 1 6 7 1 1 10 1是1輸入5 6 5 6 5 6 5 6 5 6 5 6 5 6 -1 6 7 6 7 6 7 6 -1 6 7 6 -1 6 -1 6 -1 6 -1 6 -1 6 -1 6 -1 6 -1 6 -1 6 -1 6 -1 6 -1 6 -1 6 -1 6 -1 6我得到的輸出=( –

+0

你的問題到底是什麼? – Borodin

回答

1

你有沒有到位use strictuse warnings 'all'

我想,你的問題可能是因爲測試$i = $length - 1,這是一個分配的,而應該是$i == $length - 1

1

要找到大部分元素我會使用散列:

perl -nae '%h=(); $h{$_}+=2 for @F; $h{$_}>@F and print for keys %h; print "\n"' 

每一行的輸入被分開處理。每行輸出匹配一行輸入並顯示其多數元素,如果沒有這樣的元素,則爲空。

編輯:現在解決方案使用自動分割(-a),它更短,不僅適用於數字。