Dictionaries and Maps problem solution - 30 days of code HackerRank

Input Format
The first line contains an integer, , denoting the number of entries in the phone book.
Each of the  subsequent lines describes an entry in the form of  space-separated values on a single line. The first value is a friend's name, and the second value is an -digit phone number.
After the  lines of phone book entries, there are an unknown number of lines of queries. Each line (query) contains a  to look up, and you must continue reading lines until there is no more input.
Note: Names consist of lowercase English alphabetic letters and are first names only.
Output Format
On a new line for each query, print Not found if the name has no corresponding entry in the phone book; otherwise, print the full  and  in the format name=phoneNumber.
Dictionaries and Maps problem solution - 30 days of code HackerRank

Problem solution in c++ programming languages.

#include <iostream>
#include <map>
using namespace std;

int main() {
    std::map<string, string> phoneBook;
    int n;
    cin >> n;
    
    // Read names and numbers, add to phoneBook:
    for(int i = 0; i < n; i++){
        string name;
        string phone;
        cin >> name;
        cin >> phone;
        phoneBook[name] = phone;
    }
    
    // Execute queries:
    std::map<string,string>::iterator it;
    string query;
    while( cin >> query ){
        it = phoneBook.find(query);
        
        if ( it != phoneBook.end() ){ // key is found in phoneBook    
            cout << it->first << "=" << it->second << '\n';
        }
        else{ // the iterator hit the end of the phone book without finding key
            cout << "Not found" << '\n';
        }
    }
    
    return 0;
}

Problem solution in C sharp programming language.

using System;
using System.Collections.Generic;

class Solution {
    static void Main(String[] args) {
        // Create phone book
        var phoneBook = new Dictionary<string, string>();
        
        // get number of entries
        int n = Convert.ToInt32(Console.ReadLine());
        
        // add entries to book
        for(int i = 0; i < n; i++){
            string[] inputs = Console.ReadLine().Split();
            
            phoneBook[inputs[0]] = inputs[1];
  } 
        
        // perform queries
        string queryKey;
        while ((queryKey = Console.ReadLine()) != null) {
            if (phoneBook.ContainsKey(queryKey)) {
                Console.WriteLine("{0}={1}", queryKey, phoneBook[queryKey]);
            } else{
                Console.WriteLine("Not found");
            }
        }
    }   
}

Problem solution in Java programming language.

import java.util.*;
import java.io.*;

class Solution{
    public static void main(String []args){
        Map<String,Integer> phoneBook = new HashMap<String,Integer>();
        Scanner scan = new Scanner(System.in);
        int n = scan.nextInt();
        for(int i = 0; i < n; i++){
            String name = scan.next();
            int phone = scan.nextInt();
            phoneBook.put(name, phone);
        }
        while(scan.hasNext()){
            String s = scan.next();
            Integer phoneNumber = phoneBook.get(s);
            System.out.println(
                (phoneNumber != null) 
                ? s + "=" + phoneNumber 
                : "Not found"
            );
        }
        scan.close();
    }
}

Problem solution in JavaScript programming language.

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

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

/** SOLUTION ***/

function processData(input) {
    input = input.trim().split("\n");
    var phoneBook = {};
    
    // Add entries
    for (i = 1; i <= input[0]; i++) {
        let line = input[i].trim().split(" ");
        
        phoneBook[line[0]] = line[1];
    }
    
    // Search
    for (; i < input.length; i++) {
        let result = phoneBook[input[i]];
        console.log( 
            (result != undefined)
            ? input[i] + "=" + result
            : "Not found"
        );
    }
}

Problem solution in Python programming language.

import sys 

# Read input and assemble Phone Book
n = int(input())
phoneBook = {}
for i in range(n):
    contact = input().split(' ')
    phoneBook[contact[0]] = contact[1]

# Process Queries
lines = sys.stdin.readlines()
for i in lines:
    name = i.strip()
    if name in phoneBook:
        print(name + '=' + str( phoneBook[name] ))
    else:
        print('Not found')

Problem solution in the Swift programming language.

var n = Int(readLine()!)!
var phoneBook = [String: String]()

for i in 0...n - 1 {
    // read contacts into phone book
    var contact = readLine()!.characters.split(separator: " ").map(String.init)
    phoneBook[contact[0]] = contact[1]
}

var queryName = readLine()
while queryName != nil {
    if let number = phoneBook[queryName!] {
        print("\(queryName!)=\(phoneBook[queryName!]!)")
    }
    else {
        print("Not found")
    }
    queryName = readLine()
}

Post a Comment

0 Comments