Tags

, , , ,

I’ve tried to create a program which’s having a map (key, value) pairs that contains the occurrences of the moves, I’ve fixed the moves R, P, S (Thinking of Rock, Paper, Scissor Game).

Every time when i make a move the map should increment the value of the move accordingly.

I’ve tried it with java and scala

This is the java code

import java.util.HashMap;
import java.util.Map;

class Game {

    public HashMap<String, Integer> movesCount = new HashMap<String, Integer>();

    public Game() {
        movesCount.put("R", 0);
        movesCount.put("P", 0);
        movesCount.put("S", 0);
    }


    public static void main(String[] args) {
        Game game = new Game();
        game.makeMove("R");
        System.out.println(game.getFrequentlyUsedMove());
        game.makeMove("S");
        game.makeMove("S");
        System.out.println(game.getFrequentlyUsedMove());
        game.displayMoveOccurrences();
    }

    public void makeMove(String move) {
        Integer existingCount = movesCount.get(move);
        movesCount.put(move, ++existingCount);
    }

    public void displayMoveOccurrences() {
        System.out.println(movesCount);
    }


    public String getFrequentlyUsedMove() {
        int maxCount = -1;
        String frequentMove = null;
        for (Map.Entry<String, Integer> currMove : movesCount.entrySet()) {
            Integer occurrence = currMove.getValue();
            if (occurrence > maxCount) {
                maxCount = occurrence;
                frequentMove = currMove.getKey();
            }
        }
        return frequentMove;
    }

}

and the scala code

val moves_count = scala.collection.mutable.Map("R"->0, "P"->0, "S"->0)
def makeMove(move:String) = moves_count(move) += 1
def getFrequentMove = moves_count.maxBy(_._2)._1

makeMove("R")
println("Far more Cooool!" + getFrequentMove)

makeMove("S")
makeMove("S")
println("Far more Cooool!" + getFrequentMove)

println(moves_count)

This is really amazing, and thats why people say its CONCISE.
scala program is 9 lines but java took 38 lines.

you might think that we can use a sorted Map “TreeMap” and get the value simply, but considering that this method is used rarely sortedMap’ll cause overhead of O(log(n)) complexity.

[TreeMap is implemented as RedBlackTree hence insertion takes O(log n) complexity]

instead of the displayMoveOccurences we might wanna make the moves public and can display it directly so as to reduce number of lines, but i’ve written the program as java developer mindset [how i’ll write in java].

TreeMap complexity:
http://stackoverflow.com/questions/8297223/working-of-tree-maps-time-complexity-at-insert-and-read-opertation-in-java

Advertisements