2010-12-04 36 views
0

我無法找到一對大小爲5的字符串。因此,只能有兩對。對於我發現的每一對,我都應該將分數提高2分。 這是我到目前爲止,但它是不正確的。查找對中的五個

String temp = "4 5 4 3 3"; 
    String tempLine = temp.replaceAll(" ", ""); 
    String[] hand = temp.split(" "); 
     for(int i = 0; i < hand.length; i++) 
        { 

         if(hand[i].equals(tempLine.substring(0, 1)) && i !=0) 
          score += 1; 
         if(hand[i].equals(tempLine.substring(1, 2)) && i != 1) 
          score += 1; 
         if(hand[i].equals(tempLine.substring(2, 3)) && i!= 2) 
          score += 1; 
         if(hand[i].equals(tempLine.substring(3, 4)) && i!= 3) 
          score += 1; 
         if(hand[i].equals(tempLine.substring(4)) && i != 4) 
          score += 1; 

        } 

編輯:我試圖找到具有相似值的手對,例如4將是這一手

+0

你可以再提供一些代碼嗎?還有更多解釋你想要完成的事情! – Michael 2010-12-04 20:38:07

回答

1

我覺得這個適合你正在試圖做什麼。

char[] hand = {'a','b','c','b','c'}; 
/* sort the hand to ensure pairs are next to each other */ 
for(int x=0;x<hand.length - 1;x++){ 
    for(int y=(x+1);y<hand.length;y++){ 
     if((int)hand[x] > (int)hand[y]){ 
      char temp = hand[y]; 
      hand[y] = hand[x]; 
      hand[x] = temp; 
     } 
    } 
} 
int score = 0; 
for(int x=0;x<hand.length - 1;x++){ 
    if(hand[x] == hand[x + 1]){ 
     score++; 
     /*if you want to make sure you only get pairs 
      add an "x++;" that way it'll skip over the 
      letter you just tested*/ 
    } 
} 
2

排序的手,然後再循環雖然尋找發現一對手[i] ==手[i-1]。請注意,您可能必須稍微聰明一些,以免計數3次或4次的組合,但這應該讓您開始。

0

1)爲什麼不比較手部陣列的元素其他元素?您已經完成了解釋字符串並創建數組數據的工作;用它。

2)除此之外,還有更多可能的元素對。在電腦前連續放置五個類似的物體,並親自嘗試一下。你應該能夠識別十對。您還應該能夠確定如何查找/標記配對的模式。

+0

我試圖找到具有類似價值的手中的對,例如4將在這隻手中找到一對 – 2010-12-04 20:44:01

2

創建一個實際的Hand類,並且不要使用String s表示您的卡片。一個Card的點數和花色是一個enum合適的人選:

class Card { 
    enum Suite { ... }; 
    enum Rank { ... }; 

    private final Suite s; 
    private final Rank r; 

    // ... 
} 

class Hand { 
    private Card[] cards; 
    // ... 
} 
Hand類,這使得它更容易地評估

和排序Card[]

結帳Oracle的enum教程,有卡的例子:http://download.oracle.com/javase/1.5.0/docs/guide/language/enums.html

0

下面的這個例子是如何計算配對的一種可能性。問題是如果字符串或數組中有三個相等的值或其他值,它應該如何表現(提高分數)。這應該算作三對還是不算......?

 
123 is in fact three combinations 12 && 13 && 23 
111 is in fact three combinations 11 && 11 && 11 
 


package edu.harris.pairs; 

public class FindPairs { 

    public static void main(String[] args) { 
    String s = "hello"; 
    int score = 0; 
    for (int i = 0; i < s.length() - 1; i++) { 
     for (int j = i + 1; j < s.length(); j++) { 
     if (s.charAt(i) == s.charAt(j)) { 
      score++; 
     } 
     } 
    } 
    System.out.println(score); 
    } 

} 

 

希望這有助於一點。