Sunday, May 26, 2019

Coding challenge - Sock Merchant

I hate test tasks so much I spend four hours out of five to think why I hate them so much. This time I came up with the following list of whys:

-- expectations are never clear and when they are clear they are clearly about knowing rules for the game, not actual solving something from the scratch, to be successful you need to be familiar with known working solutions, not work on your own;
-- ruminating about what your interviewer brain processes is very distracting, cause practice proves that they may be thinking lots of things, almost all of them not in your favor.

What would be better, array or collections? If you use array they will think you don't know collections. If you use collections they'll think you have a habit of over-complicating things. And if you use for or if  they'll think you've worked with legacy for too long and sustained irreparable brain damage.

Well, anyway, original task is here, and my version of code looks like this:


package com.andrjushina.projects.codingchallenges;

import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;

public class SockMerchant {
  
    public static void main(String[] args) {
      
        int numberInHeap = 10;
        int colors[] = {10,20,80,10,80,80,60,60,10,30};
        System.out.println("pairs: " + sockMerchant(numberInHeap, colors));
    }

    static int sockMerchant(int n, int[] ar) {

        Integer pairs = 0;
        Set<Integer> uniqueColors = new HashSet<Integer>();

        for(int i=0; i<ar.length; i++){
            uniqueColors.add(ar[i]);
        }

        Iterator<Integer> iterator = uniqueColors.iterator();

        Map<Integer, Integer> sockHolder = new HashMap<Integer, Integer>();

        while(iterator.hasNext()){
            Integer colorCode = (Integer) iterator.next();
            sockHolder.put(colorCode.intValue(),0);
        }

        iterator = uniqueColors.iterator();
      
        while(iterator.hasNext()){
            Integer colorCode = (Integer) iterator.next();
       
            for(int i=0; i<ar.length; i++){
              
                if(colorCode.intValue() == ar[i]){
                    Integer newQty = sockHolder.get(colorCode.intValue())+1;
                    sockHolder.replace(colorCode.intValue(), newQty);
                }
            }
        }

        iterator = uniqueColors.iterator();

        while(iterator.hasNext()){
            Integer colorCode = (Integer) iterator.next();
            Integer pairedSocksForAColor=sockHolder.get(colorCode.intValue())/2;
            pairs=pairs+pairedSocksForAColor;

        }

        return pairs;

    }

}

No comments:

Post a Comment