【问题标题】:Choosing the Correct Collections选择正确的集合
【发布时间】:2012-07-26 05:56:14
【问题描述】:

我有一种情况,我在一个房间里有一组玩家,每个玩家手中都会有一组牌。

HashMap<Integer,ArrayList<Integer>> useridToCardsinTheirHand = new HashMap<Integer, ArrayList<Integer>>();

任何玩家都可以“拨打电话”。 我需要检查发出“跟注”的玩家是否价值最低 (聚合卡片的最小值)。

为了继续上述逻辑,我再次使用 LinkedhashMap

private static LinkedhashMap<Integer,Integer> useridTotalRank = new LinkedhashMap<Integer,Integer>();

如果值相同,则会进行优先级算法。

我在所有逻辑中都使用 hashMap。

我在使用 HashMaps 时遇到问题。逻辑流程很笨拙。

我正在计划重新设计。我正在通过 MultiMap ,但仍然预料到类似的问题。 我可以对要使用的集合类型提出建议吗?

我试过的伪代码是::

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.Map.Entry;

public class NewCalling {

    static HashMap<Integer,ArrayList<Integer>> useridToPointsmap = new HashMap<Integer, ArrayList<Integer>>();
    lamposHAshMap hashmapsort = new lamposHAshMap();
    private static HashMap<Integer,Integer> useridTotalRank = new HashMap<Integer,Integer>();

    private static int jokercard = 0x27;
    private static int closedjokercard =0x25 ;
    private static List<Integer> faceCards = new ArrayList<Integer>();



    @SuppressWarnings("unchecked")
    public static void main(String args[]) {

        /**
         * Assuming the calling is made and the Player id is hard Coded
         */
        boolean callingflag = true;
        int callinguserid = 2;

        /*************** Preparing the information which will be given by the ********/
        ArrayList<Integer> cardsArray1 = new ArrayList<Integer>(); 
        ArrayList<Integer> cardsArray2 = new ArrayList<Integer>(); 
        ArrayList<Integer> cardsArray3 = new ArrayList<Integer>(); 
        ArrayList<Integer> cardsArray4 = new ArrayList<Integer>(); 


        cardsArray1.add(0x01);
        cardsArray1.add(0x1A);
        //cardsArray1.add(0x33);

        cardsArray2.add(0x21);
        cardsArray2.add(0x03);
        cardsArray2.add(0x32);

        cardsArray3.add(0x21);
        cardsArray3.add(0x03);
        cardsArray3.add(0x32);

        cardsArray4.add(0x01);
        cardsArray4.add(0x02);
        cardsArray4.add(0x32);
        cardsArray4.add(0x31);


        useridToPointsmap.put(1,cardsArray1);
        useridToPointsmap.put(2,cardsArray2);
        useridToPointsmap.put(3,cardsArray3);
        useridToPointsmap.put(4,cardsArray4);


        faceCards.add(0,10);
        faceCards.add(1,11);
        faceCards.add(2,12);
        faceCards.add(3,13);


        /*************** Preparing the information which will be given by the ********/

        if(callingflag)
        {
            int calledUserTp = totalPointsByUserid(callinguserid,jokercard);
            System.out.println("Total Points of the User Who has made a Call is ::"+calledUserTp);

            HashMap<Integer,Integer> useridTotalRankMap = totalPointsforEveryUser(jokercard);
            LinkedHashMap<Integer,Integer> useridTotalRankMapSorted = new LinkedHashMap<Integer, Integer>();
            useridTotalRankMapSorted = (LinkedHashMap<Integer, Integer>) sortByComparator(useridTotalRankMap);
            for(Map.Entry<Integer, Integer> entry :useridTotalRankMapSorted.entrySet())
            {
                System.out.println( entry.getKey() +"----"+entry.getValue());
                if(entry.getKey() == callinguserid )
                {
                    System.out.println( "GOOD CALL");
                    break;
                }

            }

        }
    }


    /** Gives the Cards Rank    **/
    static int getCardRank(int Cardhexvalue)
    {
        int rank = Cardhexvalue & 15;
        return rank;

    }
    /** Gives the Cards Suit    **/

    static int getCardSuit(int Cardhexvalue)
    {
        int suit = (Cardhexvalue>>4);
        return suit;

    }
    // METHODS REQUIRED 
    private static HashMap<Integer,Integer> totalPointsforEveryUser(int jokerCardVal)
    {
        for(Map.Entry<Integer, ArrayList<Integer>> entry :useridToPointsmap.entrySet())
        {
            int sum = 0;
            int playerId = entry.getKey();
            ArrayList<Integer> cardsList = entry.getValue();

            for (Integer s : cardsList)
            {
                if (getCardRank(s) != getCardRank(jokerCardVal)) {
                    if (faceCards.contains(s))
                    {
                        sum += 10;
                    }
                    else
                    {
                        sum += getCardRank(s);
                    }
                }             
            }
            useridTotalRank.put(playerId, sum);

        }

        return useridTotalRank;
    }


    private static int totalPointsByUserid(int userId,int jokerCardVal)
    {
        ArrayList<Integer> cardsList = useridToPointsmap.get(userId);
        int sum = 0;
        for (Integer s : cardsList)
        {

            if (getCardRank(s) != getCardRank(jokerCardVal)) {
                if (faceCards.contains(s))
                {
                    sum += 10;
                }
                else
                {
                    sum += getCardRank(s);
                }
            }            
        }   
        return sum;
    }

    @SuppressWarnings("unchecked")
    private static Map sortByComparator(Map unsortMap) {

        List list = new LinkedList(unsortMap.entrySet());

        //sort list based on comparator
        Collections.sort(list, new Comparator() {
            public int compare(Object o1, Object o2) {
                return ((Comparable) ((Map.Entry) (o1)).getValue())
                .compareTo(((Map.Entry) (o2)).getValue());
            }
        });

        //put sorted list into map again
        Map sortedMap = new LinkedHashMap();
        for (Iterator it = list.iterator(); it.hasNext();) {
            Map.Entry entry = (Map.Entry)it.next();
            sortedMap.put(entry.getKey(), entry.getValue());
        }
        return sortedMap;
    }   

    private static boolean checkForNoDuplicates(HashMap<Integer, Integer > useridTotalRankMapSorted)
    {
        Collection<Integer> valuesList = useridTotalRankMapSorted.values();
        Set<Integer> valuesSet = new HashSet<Integer>(useridTotalRankMapSorted.values());

        System.out.println("-----"+ valuesList.size() +"----"+valuesSet.size());
        if(valuesList.size() == valuesSet.size())
        {
            return true;
        }
        else
            return false;

    }

    // Stack

    public static HashMap getDuplicateValues(HashMap in)
    {
        // Clone input HashMap because we're removing stuff from it
        in = (HashMap)in.clone();
        HashMap rval = new HashMap();
        Object[] keys = in.keySet().toArray();

        // iterate through all keys
        for(int x=0;x<keys.length;x++) {
            Object value = in.get(keys[x]);
            in.remove(keys[x]);
            // if value is in input HashMap, store it in duplicate HashMap because it has another value
            if(in.containsValue(value)) {
                rval.put(keys[x],value);
            }
            // if value is in duplicate HashMap, store it also because it HAD another value earlier
            if(rval.containsValue(value)) {
                rval.put(keys[x],value);
            }
        }

        return(rval);
    }


    public static HashMap<Object, ArrayList<Object>> gettingTheDuplicates(HashMap map) {
        HashMap<Object, ArrayList<Object>> newMap =  new HashMap<Object, ArrayList<Object>>();

        Set<Entry> set = map.entrySet();
        for(Entry entry : set) {
            ArrayList list = new ArrayList();
            if(newMap.containsKey(entry.getValue())) {
                list=newMap.get(entry.getValue());
            }
            list.add(entry.getKey());
            newMap.put(entry.getValue(), list);
        }
        return newMap;
    }


    private static void priorityCheck(int playerId1,int playerId2,int jokerCardVal)
    {
        int jokerCountPlayerOne = 0;
        int jokerCountPlayerTwo = 0;
        int openJokerCountPlayerOne = 0;
        int openJokerCountPlayerTwo = 0;
        List<Integer> playerOneCards = useridToPointsmap.get(playerId1);
        List<Integer> playerTwoCards = useridToPointsmap.get(playerId2);
        System.out.println("Current game player cards-----"+playerOneCards);
        System.out.println("Tied game player cards--------"+playerTwoCards);
        int playerOneCardCount =  playerOneCards.size();
        int playerTwoCardCount =  playerTwoCards.size();
        // Hard coded
        // playerOneCardCount = 4;
        //playerTwoCardCount = 4;
        // jokerCountPlayerOne = 1;
        // jokerCountPlayerTwo = 1;
        //openJokerCountPlayerOne =1;
        //openJokerCountPlayerTwo =2;
        System.out.println("---jokerCardVal---"+jokerCardVal);
        System.out.println("---playerOneCardCount---playerTwoCardCount"+playerOneCardCount+"  "+playerTwoCardCount);


        if  (playerOneCards.contains(jokerCardVal))
        {
            openJokerCountPlayerOne++;
        }
        if  (playerTwoCards.contains(jokerCardVal))
        {
            openJokerCountPlayerTwo++;
        }
        if  (playerOneCards.contains(0))
        {
            jokerCountPlayerOne++;
        }
        if  (playerTwoCards.contains(0))
        {
            jokerCountPlayerTwo++;
        }
        if (playerOneCardCount == playerTwoCardCount)
        {
            if (jokerCountPlayerOne == jokerCountPlayerTwo)
            {
                if (openJokerCountPlayerOne == openJokerCountPlayerTwo)
                {
                    System.out.println("Still Tie Occurring---------------");
                }  else
                {
                    if (openJokerCountPlayerOne > openJokerCountPlayerTwo)
                    {
                        System.out.println("First player has high rank  based on open joker");
                    }   else
                    {
                        System.out.println("Second player has high rank  based on open joker");
                    }
                }
            }  else
            {
                if (jokerCountPlayerOne > jokerCountPlayerTwo)
                {
                    System.out.println("First player has high rank  based on joker");
                }   else
                {
                    System.out.println("Second player has high rank  based on joker");
                }
            }
        }  else
        {
            if (playerOneCardCount < playerTwoCardCount)
            {
                System.out.println("First player has high rank based on Count");
            }   else
            {
                System.out.println("Second player has high rank based on count");
            }
        }
    }



    // New Priority Check
    private static List<Integer> priorityNew(ArrayList<Integer> tocompare)
    {

        // ArrayList to array 
        Integer[] sortedArray = (Integer[]) tocompare.toArray();
        bubble_srt(sortedArray,sortedArray.length);
        List<Integer> mapValuesNew = Arrays.asList(sortedArray);

        return mapValuesNew;

    }



    public static void bubble_srt( Integer a[], int n ){
        int i, j,t=0;
        for(i = 0; i < n; i++){
            for(j = 1; j < (n-i); j++){
                //    System.out.print(" I am in first "+a[j-1]+"  "+a[j] +"*********"+whichCardHigher(a[j-1],a[j]));   
                if(WhichuserHigher(a[j-1],a[j])){
                    t = a[j-1];
                    a[j-1]=a[j];
                    a[j]=t;
                }
            }
        }

    }


    public static boolean WhichuserHigher(int user1,int user2)

    {
        if(getNumberofCards(user1) == getNumberofCards(user1) )  
        {
            if(getNumberofJoker(user1) == getNumberofJoker(user2))
            {
                if(getNumberofClosedJoker(user1) == getNumberofClosedJoker(user2))
                {
                    System.out.println("Its a Mega Tie");
                }
                else
                {
                    if(getNumberofClosedJoker(user1) > getNumberofClosedJoker(user2))
                    {
                        return true;
                    }
                    else
                    {   
                        return false;
                    }
                }
            }
            else
            {
                if(getNumberofJoker(user1) > getNumberofJoker(user2))
                {
                    return true;
                }
                else
                {   
                    return false;
                }
            }
        }
        else
        {
            if(getNumberofCards(user1) >getNumberofCards(user2))
            {
                return true;
            }
            else
            {   
                return false;
            }

        }
        return false;

    }

    public static int getNumberofCards(int user)
    {
        int noOfCards = 0;
        for(Map.Entry<Integer, ArrayList<Integer>> entry :useridToPointsmap.entrySet())
        {
            if(entry.getKey() == user)
            {
                noOfCards = entry.getValue().size();
            }
        }
        return noOfCards;

    }
    public static int getNumberofJoker(int user)
    {
        int noOfJokers = 0;
        int count = 0;
        for(Map.Entry<Integer, ArrayList<Integer>> entry :useridToPointsmap.entrySet())
        {
            if(entry.getKey() == user)
            {
                for(int i= 0 ;i< entry.getValue().size();i++)
                {
                    if(Integer.parseInt(entry.getValue().toString()) == jokercard)
                    {
                        count ++;
                    }
                }
            }
        }
        noOfJokers = count;
        return noOfJokers;

    }
    public static int getNumberofClosedJoker(int user)
    {
        int noOfClosedJokers = 0;
        int count = 0;
        for(Map.Entry<Integer, ArrayList<Integer>> entry :useridToPointsmap.entrySet())
        {
            if(entry.getKey() == user)
            {
                for(int i= 0 ;i< entry.getValue().size();i++)
                {
                    if(Integer.parseInt(entry.getValue().toString()) == closedjokercard)
                    {
                        count ++;
                    }
                }
            }
        }
        noOfClosedJokers = count;
        return noOfClosedJokers;

    }

}

【问题讨论】:

  • 能否请您发布您的代码

标签: java collections hashmap multimap


【解决方案1】:

请为 Room、Player 和 Card(可能不需要 Card)等提供简单的 Java bean。这样您可以在将来有新需求时更改类的属性。最终,您只需要管理 List Room,这样如果您获得 Room 对象,您就可以轻松地从中检索 Players 等等。

Class Room{
   String roomName;
   String location;
   String List<Player>;
   // have getters setters for each of them
}

这种方式也更易于管理,因此处理代码(如果有的话)您可以只将它们放在相关的类中。例如在房间类中,您可以有一个名为 getLeastValueCard 的方法,该方法为该房间返回哪个用户,您可以对整个房间进行循环。

希望这是有道理的。

【讨论】:

  • 我发布的代码是伪代码。我只从玩家手中的牌开始代码,而不是从房间创建部分开始。但是谢谢,我会确保我将来保持代码的清晰度和可管理性
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2023-03-28
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-04-07
  • 1970-01-01
相关资源
最近更新 更多