2013-03-15 101 views
1

比方說,我有兩個數組:比較兩個數組的ActionScript 3

var arrOne:Array = ["fish", "cat", "dog", "tree", "frog"]; 
var arrTwo:Array = ["cat", "cat", "fish", "dog", "fish"]; 

我需要能夠對它們進行比較,以確定以下內容:

  • 多少匹配項有相同位置(在上面的情況下會有1:arrOne [1]和arrTwo [1]都是貓)。
  • 多少匹配有不在同一位置(在這種情況下,上面會有2:貓和魚)。

這將比較用戶的輸入和隨機生成的數組值;基本上我想能夠說「你有一個正確的,在正確的位置,兩個正確的,但在錯誤的位置」。希望這是有道理的。任何幫助,將不勝感激!

+0

對於第二種情況,「狗」呢? – Anton 2013-03-16 08:42:36

回答

0

我只是比較常見的方法的元素。唯一的問題是我們應該如何對待第二種情況的「魚」。

這是我針對兩種情況的解決方案。 1 - 如果我們不關心重複項目,2 - 如果我們這樣做。

<?xml version="1.0" encoding="utf-8"?> 
<s:Application xmlns:fx="http://ns.adobe.com/mxml/2009" 
      xmlns:s="library://ns.adobe.com/flex/spark" 
      xmlns:mx="library://ns.adobe.com/flex/mx" minWidth="955" minHeight="600"> 
<fx:Script> 
    <![CDATA[ 
     import mx.controls.Alert; 
     import mx.events.FlexEvent; 

     private var arrOne:Array = ["fish", "cat", "dog", "tree", "frog"]; 
     private var arrTwo:Array = ["cat", "cat", "fish", "dog", "fish"]; 

     protected function compare():void 
     { 
      var rule1:int = 0; 
      var rule2:int = 0; 

      for (var i: int = 0; i < arrOne.length; i++) 
      { 
       for (var j: int = 0; j < arrTwo.length; j++) 
       { 
        if (arrOne[i] == arrTwo[j]) 
        { 
         if (i == j) 
          rule1 ++; 
         else 
          rule2 ++; 
        } 
       } 
      } 

      Alert.show("You got " + rule1.toString() + " correct and in the right spot, and " + rule2.toString() + " correct but in the wrong spot"); 

     } 

     protected function compareWithoutRepeat():void 
     { 
      var rule1:int = 0; 
      var rule2:int = 0; 
      var temp:Array = new Array(); 

      for (var i: int = 0; i < arrOne.length; i++) 
      { 
       for (var j: int = 0; j < arrTwo.length; j++) 
       { 
        if (arrOne[i] == arrTwo[j]) 
        { 
         if (i == j) 
          rule1 ++; 
         else 
         { 
          var flag:Boolean = false; //is there the same word in the past? 
          for (var k:int = 0; k < temp.length; k++) 
          { 
           if (temp[k] == arrTwo[j]) 
           { 
            flag = true; 
            break; 
           } 

          } 

          if (!flag) //the word is new, count it! 
          { 
           rule2 ++; 
           temp.push(arrTwo[j]); 
          } 

         } 
        } 
       } 
      } 

      Alert.show("You got " + rule1.toString() + " correct and in the right spot, and " + rule2.toString() + " correct but in the wrong spot"); 

     } 
    ]]> 
</fx:Script> 
<s:Button x="10" y="10" width="153" label="Compare" click="compare()"/> 
<s:Button x="10" y="39" label="Compare without repeat" click="compareWithoutRepeat()"/> 
</s:Application>