Day 8: Dictionaries and Maps (30 Days of Code)

Task:

Given n names and phone numbers, assemble a phone book that maps friends’ names to their respective phone numbers. You will then be given an unknown number of names to query your phone book for. For each name queried, print the associated entry from your phone book on a new line in the form name=phoneNumber; if an entry for name is not found, print Not found instead.

Note: Your phone book should be a Dictionary/Map/HashMap data structure.


Solution:

1)Javascript:

function processData(input) {
    //Enter your code here
    let phoneDirectory={},i=0;
    let test=input.replace(/\n/g," ").split(" ");
    for(i=0;i<test[0];i++){
        phoneDirectory[test[2*i+1]]=test[2*i+2];
    }
    for(let j=2*i+1;j<test.length;j++)
    {
        if(phoneDirectory[test[j]]!== undefined)
         console.log(test[j]+'='+phoneDirectory[test[j]]);
         else
         console.log("Not found");
    }
}

process.stdin.resume();
process.stdin.setEncoding("ascii");
_input = "";
process.stdin.on("data", function (input) {
    _input += input;
});

process.stdin.on("end", function () {
   processData(_input);
});

2)Java:

//Complete this code or write your own from scratch
import java.util.*;
import java.io.*;

class Solution{
    public static void main(String []argh){
        Map<String,Integer> myMap = new HashMap<String,Integer>(); 
        Scanner in = new Scanner(System.in);
        int n = in.nextInt();
        for(int i = 0; i < n; i++){
            String name = in.next();
            int phone = in.nextInt();
            // Write code here
            myMap.put(name,phone);
        }
        while(in.hasNext()){
            String s = in.next();
            // Write code here
            if(myMap.get(s)!=null)
             System.out.println(s+'='+myMap.get(s));
            else
             System.out.println("Not found");
        } 
        in.close();
    }
}

Leave a Reply