Interview Question for Java Developers


Country: India




Comment hidden because of low score. Click to expand.
0
of 0 vote

solution is store entry in Map as <String, <Lowest Id,Marks>>
For each line in the list, extract id,marks,subject name. Check the subject name(ie. key) in Map. If the value already exists, then simply compare the current Id with Id in the corresponding entry. If current Id is lower than that simply update the value pair <Lowest Id,Marks> with current ID and marks.

- Anonymous April 01, 2016 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

#include<iostream>
#include<fstream>
#include<string>
#include<vector> 
#include<map>

using namespace std;

void process(vector<string>& Arr, map<string,int>& output)
{
   map<string,map<int, int>> result;
   string a[3]; //store data field wise
   int id, marks;
   for (auto &it : Arr)
   {
      int i = 0;
      int k = 0;
      a[0] = a[1] = a[2] = "";
      while (it[i])
      {        
         if (it.at(i) !='|')
            a[k] += it[i];
         else
            ++k;

         ++i;  
      }
      string::size_type sz;
      id = stoi(a[0], &sz); //convert string to integer
      marks = stoi(a[2], &sz); 
      result[a[1]].insert( std::pair<int, int>(id, marks)); //insert in a map
   }
   //output the subject and marks for lowest id
   for (auto &rit : result)
   {
      map<int, int>::iterator pit = rit.second.begin();
      output[rit.first] = pit->second;
   }
}

int main()
{
   ifstream In;
   string name, line;
   vector<string> Arr;
   map<string, int> op;
   cout << "Enter Input File name: ";
   cin >> name;
   In.open(name);

   if (In.is_open())
   {
      while (getline(In, line))
      {
         Arr.push_back(line);
      }
      In.close();
      process(Arr, op);
   }
   else
      cout << "\nFile open Error!";
   return 0;   

}

Please comment on solution.

- ms April 01, 2016 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

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

public class PChallenge {

public void Operation(String path){
TreeMap<Integer,String> tm = new TreeMap<Integer,String>();
//String[] reader;
try {
BufferedReader br = new BufferedReader(new FileReader(path));
String line;
while((line = br.readLine())!=null){
String[] reader = line.split(":");
/*for(int i=0;i<reader.length;i++){
System.out.print(reader[i]);
}*/
if(tm.containsKey(Integer.parseInt(reader[0]))){
String str = tm.get(Integer.parseInt(reader[0]));
str = str +" "+ reader[1]+reader[2];
tm.put(Integer.parseInt(reader[0]), str);
}else{
tm.put(Integer.parseInt(reader[0]),reader[1]+reader[2]);
}
}

} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println("OutPut : StudentID = "+tm.firstKey()+" Subject&Marks = "+tm.firstEntry().getValue());

}

public static void main(String args[]){
PChallenge pc = new PChallenge();
Scanner sn = new Scanner(System.in);
System.out.println("Please enter the Location of the File");
String loc = sn.nextLine();
pc.Operation(loc);

}
}

- Anonymous April 01, 2016 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

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

public class PChallenge {

	public void Operation(String path){
		TreeMap<Integer,String> tm = new TreeMap<Integer,String>();
		//String[] reader;
		try {
			BufferedReader br = new BufferedReader(new FileReader(path));
			String line;
			while((line = br.readLine())!=null){
				String[] reader = line.split(":");
				/*for(int i=0;i<reader.length;i++){
					System.out.print(reader[i]);
				}*/
				if(tm.containsKey(Integer.parseInt(reader[0]))){
					String str = tm.get(Integer.parseInt(reader[0]));
					str = str +" "+ reader[1]+reader[2];
					tm.put(Integer.parseInt(reader[0]), str);
				}else{
					tm.put(Integer.parseInt(reader[0]),reader[1]+reader[2]);	
				}
			}
			
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		System.out.println("OutPut : StudentID = "+tm.firstKey()+" Subject&Marks = "+tm.firstEntry().getValue());
		
	}
	
	public static void main(String args[]){
		PChallenge pc = new PChallenge();
		Scanner sn = new Scanner(System.in);
		System.out.println("Please enter the Location of the File");
		String loc = sn.nextLine();
		pc.Operation(loc);
		
	}
}

- Sachin Banavi April 01, 2016 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

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

public class PChallenge {

	public void Operation(String path){
		TreeMap<Integer,String> tm = new TreeMap<Integer,String>();
		//String[] reader;
		try {
			BufferedReader br = new BufferedReader(new FileReader(path));
			String line;
			while((line = br.readLine())!=null){
				String[] reader = line.split(":");
				/*for(int i=0;i<reader.length;i++){
					System.out.print(reader[i]);
				}*/
				if(tm.containsKey(Integer.parseInt(reader[0]))){
					String str = tm.get(Integer.parseInt(reader[0]));
					str = str +" "+ reader[1]+reader[2];
					tm.put(Integer.parseInt(reader[0]), str);
				}else{
					tm.put(Integer.parseInt(reader[0]),reader[1]+reader[2]);	
				}
			}
			
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		System.out.println("OutPut : StudentID = "+tm.firstKey()+" Subject&Marks = "+tm.firstEntry().getValue());
		
	}
	
	public static void main(String args[]){
		PChallenge pc = new PChallenge();
		Scanner sn = new Scanner(System.in);
		System.out.println("Please enter the Location of the File");
		String loc = sn.nextLine();
		pc.Operation(loc);
		
	}
}

- sachinbanvi April 01, 2016 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

First, for each line in the input text file, do string parsing and extract name of the subject and Id. Convert the subject name to an Integer value and use it as key for Map. Store the corresponding 'Id' as a value in it. When ever you encounter a next line with same subject ( means that which already have an entry in Map for that subject) extract the correspond value in Map, if the value is greater than the current ID then replace that with current Id.

But, there is one problem in this, what if two different strings yield to same integer value?
Probably we could implement our own Map using arrays to handle this. Like allowing to store a linked list of entries in each block, whose key values are same. Measuring index by taking modulo of integer value and length of array...

- Anonymous April 02, 2016 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

public static void main(String[] args) {
/*
* int[] p = new int[12]; List<Integer> li = new ArrayList<Integer>();
* li.addAll(li); li.indexOf(2); Set<Integer> liset = new
* TreeSet<Integer>();
*/

String p = "22|Data Structures|45\n" + "23|English|52\n"
+ "22|English|51\n" + "26|Data Structures|72\n"
+ "23|Data Structures|61\n" + "21|English|81";
StringTokenizer token = new StringTokenizer(p, "\n");
List<String> data = new ArrayList<String>();
while(token.hasMoreTokens()){
String inputData = token.nextToken();
data.add(inputData);
}

Map<String, Integer> result = processData(data);
System.out.println(result);
}

public static Map<String,Integer> processData(List<String> inputData){
Map<String,Integer> dataMap = new HashMap<>();
Map<String,Integer> resultDataMap = new HashMap<>();

for (String subjectStr : inputData) {
StringTokenizer tck = new StringTokenizer(subjectStr,"|");
String[] tokenizedString = subjectStr.split("\\|");
int studentId = Integer.parseInt(tokenizedString[0]);
String subjectDetail = tokenizedString[1];
int marks = Integer.parseInt(tokenizedString[2]);
if(!dataMap.containsKey(subjectDetail)){
dataMap.put(subjectDetail, studentId);
resultDataMap.put(subjectDetail, marks);
}else{
Integer oldStudentId = dataMap.get(subjectDetail);
if(oldStudentId>studentId){
resultDataMap.replace(subjectDetail, marks);
dataMap.replace(subjectDetail, studentId);
}
}
}


return resultDataMap;

}

- niteshbisht70 May 09, 2016 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

package com.zbase.concurrency.implvsextnds;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.StringTokenizer;
import java.util.TreeSet;

public class MainClass {
public static void main(String[] args) {
/*
* int[] p = new int[12]; List<Integer> li = new ArrayList<Integer>();
* li.addAll(li); li.indexOf(2); Set<Integer> liset = new
* TreeSet<Integer>();
*/

String p = "22|Data Structures|45\n" + "23|English|52\n"
+ "22|English|51\n" + "26|Data Structures|72\n"
+ "23|Data Structures|61\n" + "21|English|81";
StringTokenizer token = new StringTokenizer(p, "\n");
List<String> data = new ArrayList<String>();
while (token.hasMoreTokens()) {
String inputData = token.nextToken();
data.add(inputData);
}

Map<String, Integer> result = processData(data);
System.out.println(result);
}

public static Map<String, Integer> processData(List<String> inputData) {
Map<String, Integer> dataMap = new HashMap<>();
Map<String, Integer> resultDataMap = new HashMap<>();

for (String subjectStr : inputData) {
StringTokenizer tck = new StringTokenizer(subjectStr, "|");
String[] tokenizedString = subjectStr.split("\\|");
int studentId = Integer.parseInt(tokenizedString[0]);
String subjectDetail = tokenizedString[1];
int marks = Integer.parseInt(tokenizedString[2]);
if (!dataMap.containsKey(subjectDetail)) {
dataMap.put(subjectDetail, studentId);
resultDataMap.put(subjectDetail, marks);
} else {
Integer oldStudentId = dataMap.get(subjectDetail);
if (oldStudentId > studentId) {
resultDataMap.replace(subjectDetail, marks);
dataMap.replace(subjectDetail, studentId);
}
}
}

return resultDataMap;

}
}

- niteshbisht70 May 09, 2016 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedHashMap;
import java.util.LinkedHashSet;
import java.util.Map;
import java.util.Map.Entry;
import java.util.TreeSet;

public class careercup {

	public static void processdata(ArrayList<String> ak) {

		LinkedHashMap<String, Integer> m = new LinkedHashMap<String, Integer>();
		LinkedHashMap<String, Integer> op = new LinkedHashMap<String, Integer>();

		LinkedHashSet<String> hs = new LinkedHashSet<String>();

		TreeSet<Integer> t;
		for (String i : ak) {

			String a[] = i.split("/");

			hs.add(a[1]);

		}

		for (String i : hs) {
			t = new TreeSet<Integer>();

			for (String j : ak) {

				String a[] = j.split("/");

				if (i.equalsIgnoreCase(a[1])) {

					t.add(Integer.parseInt(a[0]));
				}

			}

			m.put(i, t.first());

		}

		for (Entry<String, Integer> k : m.entrySet()) {

			for (String i : ak) {

				String a[] = i.split("/");

				if (a[1].equals(k.getKey())
						&& a[0].equals(Integer.toString(k.getValue())))

				{

					op.put(a[1], Integer.parseInt(a[2]));

				}

			}

		}

		System.out.println(op);
	}

	

	public static void main(String[] args) throws IOException {

		ArrayList<String> al = new ArrayList<String>();

		FileReader fr = new FileReader(
				"C:\\Users\\412378\\Desktop\\ja aa\\path\\jav.txt");

		BufferedReader br = new BufferedReader(fr);

		String s;

		while ((s = br.readLine()) != null) {

			al.add(s);

		}

		processdata(al);

	}

}

- Akib May 12, 2016 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

package org.trees;

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.Scanner;
import java.util.TreeMap;

public class PChallenge {

public void Operation(String path) {
TreeMap<Integer, String> tm = new TreeMap<Integer, String>();
TreeMap<String, String> n = new TreeMap<String, String>();
// String[] reader;
try {
BufferedReader br = new BufferedReader(new FileReader(path));
String line;
while ((line = br.readLine()) != null) {
String[] reader = line.split(":");

/*
* for (int i = 0; i < reader.length; i++) {
* System.out.print(reader[i]); }
*/

if (n.containsKey(reader[1])) {

String[] tmp = n.get(reader[1]).split(",");
if (Integer.parseInt(tmp[0]) > Integer.parseInt(reader[0])) {
n.put(reader[1], reader[0] + "," + reader[2]);
}
} else {
n.put(reader[1], reader[0] + "," + reader[2]);
}

}

} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
for (String s : n.keySet()) {
System.out.println(s + ": " + n.get(s).split(",")[1]);
}

}

public static void main(String args[]) {
PChallenge pc = new PChallenge();
Scanner sn = new Scanner(System.in);
System.out.println("Please enter the Location of the File");
String loc = sn.nextLine();
pc.Operation(loc);

}
}

- honey June 30, 2016 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

/* Author: Mr. Pushkar Girish Zagade
 * Contact No. : 9673385198
 * Email Id: pushkarzagade21@gmail.com
 */


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

public class Main {
	public static Map<String, Integer> processData(ArrayList<String> array) {

		Map<String, Integer> retVal = new HashMap<String, Integer>(); 	// Final
																		// Map
																		// For
																		// Data
																		// Storage

		Map<String, Integer> map = new HashMap<String, Integer>();		// One More
																		// Map To
																		// Store
																		// Subject
																		// and Marks
																		// and
																		// process
																		// it.

		for (int i = 0; i < array.size(); i++) {
			String input = array.get(i);
			System.out.println(input); 									// Print All Data On Console
			boolean flag1 = false, flag2 = false;
			String id = "", subject = "", marks = "";
			for (int j = 0; j < input.length(); ++j)		 			// Traversing and Parsing
																		// The Input
			{
				if (flag2) {
					marks = marks + input.charAt(j);
					continue;
				}
				if (!flag1) {
					if (input.charAt(j) == '|') 						//Traverse Data and split at location '|'
						flag1 = true;
					else
						id = id + input.charAt(j);

				} else if (flag1) {
					if (input.charAt(j) == '|')
						flag2 = true;
					else
						subject = subject + input.charAt(j);
				}

			}
			int Id = Integer.parseInt(id); 							    // Parse String To Integer as We Declared it as Integer
			int Marks = Integer.parseInt(marks);						// Parse String To Integer as We Declared it as Integer
			if (map.get(subject) == null) {
				map.put(subject, new Integer(Id));
				retVal.put(subject, new Integer(Marks));
			} else {
				int m = map.get(subject);
				if (Marks < m) {									    //Check Condition For Minimum Marks of Students
					map.put(subject, new Integer(Id));					// Show Dependency Between Id-Subject-Marks
					retVal.put(subject, new Integer(Marks));
				}
			}

		}

		return retVal;													// Return Final Map
	}

	public static void main(String[] args) {
		ArrayList<String> inputData = new ArrayList<String>();
		String line;
		try {
			Scanner in = new Scanner(new BufferedReader(new FileReader("input.txt")));
			while (in.hasNextLine())
				inputData.add(in.nextLine());
			Map<String, Integer> retVal = processData(inputData);
			PrintWriter output = new PrintWriter(new BufferedWriter(new FileWriter("output.txt")));
			for (Map.Entry<String, Integer> e : retVal.entrySet())
				output.println(e.getKey() + ": " + e.getValue());
			output.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
}

- pushkarzagade21 July 06, 2016 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.*;
public class student {
public void processData() throws Exception{
Map<String, Integer> map = new HashMap<String,Integer>();
Map<String, Integer> map1 = new HashMap<String,Integer>();
BufferedReader buf = new BufferedReader(new FileReader("C:\\Users\\Desktop\\student.txt"));
BufferedReader buf1 = new BufferedReader(new FileReader("C:\\Users\\Desktop\\student.txt"));

String line;
int min = Integer.MAX_VALUE;
while((line = buf.readLine()) != null){

String[] reader = line.split("\\|");

if(map.containsKey(reader[1])){
if(min > Integer.valueOf(reader[0]) ){
min = Integer.valueOf(reader[0]);

map.put(reader[1], min);

}else{
continue;
}
}else{
min = Integer.valueOf(reader[0]);
map.put(reader[1], Integer.valueOf(reader[0]));

}
}
System.out.println(map);
while((line = buf1.readLine()) != null){

String[] reader = line.split("\\|");
for(Map.Entry<String, Integer> entry : map.entrySet()){
if(entry.getKey().equals(reader[1]) && entry.getValue().equals(Integer.valueOf(reader[0]))){
map1.put(reader[1], Integer.valueOf(reader[2]));
}
}
System.out.println(map1);
}
}
public static void main(String[] args) {
// TODO Auto-generated method stub

student st = new student();
try {
st.processData();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

}

}

- hiteshp2489 August 10, 2016 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.*;
public class student {
public void processData() throws Exception{
	Map<String, Integer> map = new HashMap<String,Integer>();
	Map<String, Integer> map1 = new HashMap<String,Integer>();
	BufferedReader buf = new BufferedReader(new FileReader("C:\\Users\\Hitesh\\Desktop\\student.txt"));
	BufferedReader buf1 = new BufferedReader(new FileReader("C:\\Users\\Hitesh\\Desktop\\student.txt"));
	
	String line;
	 int min = Integer.MAX_VALUE;
	 while((line = buf.readLine()) != null){
		 
		 String[] reader = line.split("\\|");
		
		if(map.containsKey(reader[1])){
			if(min > Integer.valueOf(reader[0]) ){
				min = Integer.valueOf(reader[0]);
				
				map.put(reader[1], min);
				
			}else{
				continue;
			}
		}else{
			min = Integer.valueOf(reader[0]);
			map.put(reader[1], Integer.valueOf(reader[0]));
			
		}
	 }
	 System.out.println(map);
	 while((line = buf1.readLine()) != null){

		 String[] reader = line.split("\\|");
		 for(Map.Entry<String, Integer> entry : map.entrySet()){
			 if(entry.getKey().equals(reader[1]) && entry.getValue().equals(Integer.valueOf(reader[0]))){
				 map1.put(reader[1], Integer.valueOf(reader[2]));
				 }
			 }
		  System.out.println(map1);
	 }
}
	public static void main(String[] args) {
		// TODO Auto-generated method stub

student st = new student();
try {
	st.processData();
} catch (Exception e) {
	// TODO Auto-generated catch block
	e.printStackTrace();
}

}

}

}

- hiteshp2489 August 10, 2016 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Map;
import java.util.TreeMap;

public class CCHashMapQ1 {
	public static void main(String[] args){
		ArrayList<String> records = new ArrayList<String>();
		
		try(BufferedReader br = new BufferedReader(new FileReader("input.txt"))){
			String currentLine;
			
			while((currentLine = br.readLine()) != null){
				records.add(currentLine);
			}
			
			processData(records);
			
		} catch(IOException e){
			e.printStackTrace();
		}
	}
	
	public static void processData(ArrayList<String> records){
		//Tree map has order
		Map<String, Integer> map = new TreeMap<String, Integer>();
		int id = 0;
		int mark = 0;
		String subject = "";
		String[] field;
	
		for(String element: records){
			field = element.split("\\|");
			int newID = Integer.parseInt(field[0]);
			subject = field[1];
			mark = Integer.parseInt(field[2].trim());
			
			//First loop
			if(id == 0){
				id = newID;
				map.put(subject, mark);
			}
			
			if(newID <= id){
				id = newID;
				map.put(subject, mark);
			}	
		}
		
		for(String key: map.keySet()){
			System.out.println(key + ": " + map.get(key));
		}
	}
}

- KGB August 11, 2016 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.FileWriter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map.Entry;

/**
*
* @author 11000179
* @date Sep 24, 2016
* @time 3|32|00 PM
*/
public class Main {

/**
* Constructor
*/
public Main() {
}

public static HashMap<String, String> processData(ArrayList<String> records) {
HashMap<String, String> hashmap = new HashMap<String, String>();
for (String record : records) {
String[] arr = record.split("\\|");
if (hashmap.containsKey(arr[1])) {
String studidMarks = hashmap.get(arr[1]);

String[] arrstud = studidMarks.split("\\|");
if (Integer.parseInt(arrstud[1]) < Integer.parseInt(arr[2])) {
hashmap.put(arr[1], arr[0] + "|" + arr[2]);
}
} else
hashmap.put(arr[1], arr[0] + "|" + arr[2]);
}

for (Entry<String, String> entry : hashmap.entrySet()) {
String subject = entry.getValue().split("\\|")[0];
hashmap.put(entry.getKey(), subject);
}
return hashmap;
}

public static void main(String[] args) {
ArrayList<String> records = new ArrayList<String>();
BufferedReader reader = null;

try {
reader = new BufferedReader(new FileReader("c://input.txt"));
String line;
while ((line = reader.readLine()) != null) {
records.add(line);
}

HashMap<String, String> hashMap = processData(records);
FileWriter fileWriter = new FileWriter("c://output.txt");
for (Entry<String, String> entry : hashMap.entrySet()) {
fileWriter.append(entry.getKey() +":" +entry.getValue() +"\n");
}
fileWriter.close();
} catch (Exception e) {
e.printStackTrace();
}

}

}

- Guest September 24, 2016 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.FileWriter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map.Entry;

/**
 * 
 * @author 11000179
 * @date Sep 24, 2016
 * @time 3|32|00 PM
 */
public class Main {

    /**
     * Constructor
     */
    public Main() {
    }

    public static HashMap<String, String> processData(ArrayList<String> records) {
	HashMap<String, String> hashmap = new HashMap<String, String>();
	for (String record : records) {
	    String[] arr = record.split("\\|");
	    if (hashmap.containsKey(arr[1])) {
		String studidMarks = hashmap.get(arr[1]);

		String[] arrstud = studidMarks.split("\\|");
		if (Integer.parseInt(arrstud[1]) < Integer.parseInt(arr[2])) {
		    hashmap.put(arr[1], arr[0] + "|" + arr[2]);
		}
	    } else
		hashmap.put(arr[1], arr[0] + "|" + arr[2]);
	}

	for (Entry<String, String> entry : hashmap.entrySet()) {
	    String subject = entry.getValue().split("\\|")[0];
	    hashmap.put(entry.getKey(), subject);
	}
	return hashmap;
    }

    public static void main(String[] args) {
	ArrayList<String> records = new ArrayList<String>();
	BufferedReader reader = null;

	try {
	    reader = new BufferedReader(new FileReader("c://input.txt"));
	    String line;
	    while ((line = reader.readLine()) != null) {
		records.add(line);
	    }
	    
	    HashMap<String, String> hashMap = processData(records);
		FileWriter fileWriter = new FileWriter("c://output.txt");
		for (Entry<String, String> entry : hashMap.entrySet()) {
		    fileWriter.append(entry.getKey() +":" +entry.getValue() +"\n");
		}
		fileWriter.close();
	} catch (Exception e) {
	    e.printStackTrace();
	} 
	
    }

}

- Guest September 24, 2016 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.FileWriter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map.Entry;

/**
 * 
 * @author 11000179
 * @date Sep 24, 2016
 * @time 3|32|00 PM
 */
public class Main {

    /**
     * Constructor
     */
    public Main() {
    }

    public static HashMap<String, String> processData(ArrayList<String> records) {
	HashMap<String, String> hashmap = new HashMap<String, String>();
	for (String record : records) {
	    String[] arr = record.split("\\|");
	    if (hashmap.containsKey(arr[1])) {
		String studidMarks = hashmap.get(arr[1]);

		String[] arrstud = studidMarks.split("\\|");
		if (Integer.parseInt(arrstud[1]) < Integer.parseInt(arr[2])) {
		    hashmap.put(arr[1], arr[0] + "|" + arr[2]);
		}
	    } else
		hashmap.put(arr[1], arr[0] + "|" + arr[2]);
	}

	for (Entry<String, String> entry : hashmap.entrySet()) {
	    String subject = entry.getValue().split("\\|")[0];
	    hashmap.put(entry.getKey(), subject);
	}
	return hashmap;
    }

    public static void main(String[] args) {
	ArrayList<String> records = new ArrayList<String>();
	BufferedReader reader = null;

	try {
	    reader = new BufferedReader(new FileReader("c://input.txt"));
	    String line;
	    while ((line = reader.readLine()) != null) {
		records.add(line);
	    }
	    
	    HashMap<String, String> hashMap = processData(records);
		FileWriter fileWriter = new FileWriter("c://output.txt");
		for (Entry<String, String> entry : hashMap.entrySet()) {
		    fileWriter.append(entry.getKey() +":" +entry.getValue() +"\n");
		}
		fileWriter.close();
	} catch (Exception e) {
	    e.printStackTrace();
	} 
	
    }

}

- Guest September 24, 2016 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

public class PChallenge {
    public class StudentSubject {
        public Integer id;
        public String subject;
        public Integer score;

        public StudentSubject(Integer id, String subject, Integer score) {
            this.id = id;
            this.subject = subject;
            this.score = score;
        }
    }

    Map<String, StudentSubject> sm = new HashMap<String, StudentSubject>();

    public void process(String row) {
        String[] reader = row.split("[|]");
        Integer studentId = Integer.parseInt(reader[0]);
        String subject = reader[1];
        StudentSubject ss = new StudentSubject(
                studentId,
                subject,
                Integer.parseInt(reader[2])
        );
        if (sm.containsKey(subject)) {
            if (sm.get(subject).id > studentId) {
                sm.put(subject, ss);
            }
        } else {
            sm.put(subject, ss);
        }
    }

    public void processData() {
        System.out.println("-------------");
        for(Map.Entry<String,StudentSubject> entry :sm.entrySet()) {
            System.out.println(entry.getKey() + ": " + entry.getValue().score);
        }
    }

    public static void main(String args[]) {
        PChallenge pc = new PChallenge();
        Scanner sn = new Scanner(System.in);
        System.out.println("Please enter the Location of the File");
        List<String> rows = new ArrayList<String>();
        while (sn.hasNextLine()) {
            String loc = sn.nextLine();
            if (loc == null || loc.isEmpty()) {
                break;
            }
            pc.process(loc);
        }
        pc.processData();
    }
}

- kotabek March 04, 2017 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

#include <iostream>
#include <string>
#include <map>
#include <vector>
#include <fstream>
#include <cstdlib>

#define NUM_FIELDS 3
struct SplitLine {
std::string fields[NUM_FIELDS];
};

/* DONT MAKE ANY CHANGES ABOVE THIS LINE */

/* If you wish you can include any more files here.
(from standard libraries only) */

std::map<std::string, int> process_data(std::vector<struct SplitLine> data) {

map<string,map<int, int>> result;
std::map<std::string, int> ret_val;
string a[3]; //store data field wise
int id, marks;
for()
for (int i=0;i<data.size();i++)
{
string s1=data.
int i = 0;
int k = 0;
a[0] = a[1] = a[2] = "";
while (it[i])
{
if (it.at(i) !='|')
a[k] += it[i];
else
++k;

++i;
}
string::size_type sz;
id = stoi(a[0], &sz); //convert string to integer
marks = stoi(a[2], &sz);
result[a[1]].insert( std::pair<int, int>(id, marks)); //insert in a map
}
//output the subject and marks for lowest id
for (auto &rit : result)
{
map<int, int>::iterator pit = rit.second.begin();
ret_val[rit.first] = pit->second;
}

return ret_val;
}

/* DONT MAKE ANY CHANGES BELOW THIS LINE */

int main(void) {
std::ifstream in("input.txt");
std::vector<struct SplitLine> input_data;
while (in) {
struct SplitLine line;
for (int i=0; i<NUM_FIELDS; i++) {
if (i==NUM_FIELDS-1)
std::getline(in, line.fields[i]);
else
std::getline(in, line.fields[i], '|');
}
if (line.fields[0] != "")
input_data.push_back(line);
}
std::ofstream out("output.txt");
std::map<std::string, int> ret_val = process_data(input_data);
for (std::map<std::string, int>::iterator it = ret_val.begin();
it != ret_val.end();
it++) {
out << it->first << ": " << it->second << std::endl;
}
return 0;
}

- Anonymous October 12, 2017 | Flag Reply


Add a Comment
Name:

Writing Code? Surround your code with {{{ and }}} to preserve whitespace.

Books

is a comprehensive book on getting a job at a top tech company, while focuses on dev interviews and does this for PMs.

Learn More

Videos

CareerCup's interview videos give you a real-life look at technical interviews. In these unscripted videos, watch how other candidates handle tough questions and how the interviewer thinks about their performance.

Learn More

Resume Review

Most engineers make critical mistakes on their resumes -- we can fix your resume with our custom resume review service. And, we use fellow engineers as our resume reviewers, so you can be sure that we "get" what you're saying.

Learn More

Mock Interviews

Our Mock Interviews will be conducted "in character" just like a real interview, and can focus on whatever topics you want. All our interviewers have worked for Microsoft, Google or Amazon, you know you'll get a true-to-life experience.

Learn More