2013-03-15 100 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>