选择正确的集合

时间:2012-07-26 05:56:14

标签: java collections hashmap multimap

我的情况是我在一个房间里有一套玩家,每个玩家手里都有一套牌。

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;

    }

}

1 个答案:

答案 0 :(得分:1)

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

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

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

希望这是有道理的。