Microsoft Interview Question
Country: India
private string[] ReadFiles(string filepath)
{
return File.ReadAllLines(filepath);
}
private void GetAvgMarks_DataStructure(string[] fileData,out double avg)
{
string Row = ""; int index=0,amount=0;
double total = 0;
foreach (string x in fileData)
{
Row=x.Trim();
if (Row != "" && Row.Contains("Data Structures"))
{
amount++;
index = Row.LastIndexOf(" ");
total += Convert.ToDouble(Row.Substring(index+1));
}
}
avg = total / amount;
}
Well, it isn't C# code, but Java is hopefully close enough, I didn't feel like opening Visual Studio.
If I understand the question correctly then you don't really need to care about any of the lines without "Data Structures" in it since that's all you really care about in this case. So as you read the file in line by line you only need to do stuff to those lines.
Next you trim off ending and beginning spaces so that the next part works correctly. Now we need to get the index of the last space. This way we can get the number off the end and not have to worry about anything else. So we go down the string until we hit the last space.
After that we just substring from the space and we have the grade. Convert it to an int, add it to the total and go on.
Scanner s = FileIO("input.txt");
int total = 0, amount = 0;
while(s.hasNextLine())
{
String input = s.nextLine().trim();
if(input.contains("Data Structures"))
{
amount++;
int fromIndex = 0;
while(input.indexOf(" ", fromIndex+1) != -1)
{
fromIndex = input.indexOf(" ", fromIndex+1)+1;
}
total += Integer.parseInt(input.substring(fromIndex));
}
}
System.out.println(total/amount);
static void Main(string[] args)
{
String[] text= System.IO.File.ReadAllLines("input.txt");
int count = 0;
int total = 0;
bool checkfileFormat = false;
foreach(String line in text)
{
checkfileFormat = true;
if (line.Contains("Data Structures"))
{
string[] strArray = line.Trim().Split(' ');
int value = 0;
checkfileFormat = Int32.TryParse(strArray[strArray.Length - 1], out value);
if (checkfileFormat == true)
{
total = total + value;
count++;
}
else
{
checkfileFormat = false;
break;
}
}
}
if (checkfileFormat == true)
{
if (count > 0)
Console.WriteLine("Avg: " + Convert.ToString(total / count));
else
Console.WriteLine("No student having Data Structure as Subject");
}
else
{
Console.WriteLine("Input file is not in correct format");
}
Console.ReadLine();
}
static void Main(string[] args)
{
String[] text= System.IO.File.ReadAllLines("input.txt");
int count = 0;
int total = 0;
bool checkfileFormat = false;
foreach(String line in text)
{
checkfileFormat = true;
if (line.Contains("Data Structures"))
{
string[] strArray = line.Trim().Split(' ');
int value = 0;
checkfileFormat = Int32.TryParse(strArray[strArray.Length - 1], out value);
if (checkfileFormat == true)
{
total = total + value;
count++;
}
else
{
checkfileFormat = false;
break;
}
}
}
if (checkfileFormat == true)
{
if (count > 0)
Console.WriteLine("Avg: " + Convert.ToString(total / count));
else
Console.WriteLine("No student having Data Structure as Subject");
}
else
{
Console.WriteLine("Input file is not in correct format");
}
Console.ReadLine();
}
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
double averageMarks = getAverageMarksPerSubject("Data Structures");
Console.Write(averageMarks.ToString());
}
private static double getAverageMarksPerSubject(string subjectName)
{
string line = string.Empty;
int index = 0;
int numberOfStudents = 0;
int totalMarksInSubject = 0;
string marks = string.Empty;
using (StreamReader sr = new StreamReader(@"C:\Sunil\MSFT\Marks_Students.txt"))
{
while ((line = sr.ReadLine()) != null)
{
if (line.Contains(subjectName))
{
index = line.Trim().LastIndexOf(" ");
marks = line.Trim().Substring(index + 1, line.Trim().Length - (index + 1));
if (string.IsNullOrEmpty(marks))
{
totalMarksInSubject += 0;
}
else
{
try
{
totalMarksInSubject += Convert.ToInt32(marks);
}
catch (Exception)
{
totalMarksInSubject += 0;
}
}
numberOfStudents++;
}
}
return totalMarksInSubject / numberOfStudents;
}
}
}
}
This works in C#. Also handles some edge cases, except Lower case and upper case strings.
struct Val
{
public int value;
public int count;
}
class Program
{
static void Main(string[] args)
{
const string inputstring = @"22 Data Structures 45
23 Maths 2 52
23 Maths 3 57
22 English 51
26 Data Structures 72
23 Data Structures 63
26 English 81";
Dictionary<string, Val> hashTable = new Dictionary<string, Val>();
string[] lines = inputstring.Split('\n');
foreach( var line in lines )
{
string trimmed = line.Trim().Trim('\r');
int firstindex = trimmed.IndexOf(' ');
int endIndex = trimmed.LastIndexOf(' ');
string subjectName = line.Substring(firstindex, endIndex - firstindex ).Trim();
endIndex = trimmed.LastIndexOf(' ');
string scoreString = line.Substring(endIndex, line.Count() - endIndex).Trim();
int score = -1;
if (!Int32.TryParse(scoreString, out score))
continue;
if (hashTable.ContainsKey(subjectName))
{
Val v = new Val();
if (!hashTable.TryGetValue(subjectName, out v))
continue;
v.value += score;
v.count++;
hashTable[subjectName] = v;
}
else
{
hashTable.Add(subjectName, new Val() { count = 1, value = score } );
}
}
const string avgSubjectName = "Data Structures";
if ( hashTable.ContainsKey(avgSubjectName))
{
Val v = new Val();
if (hashTable.TryGetValue(avgSubjectName, out v))
Console.WriteLine(v.value / v.count);
else
Console.WriteLine("Error");
}
else
{
Console.WriteLine("Error");
}
}
}
JavaScript solution.
var f = [
'22 Data Structures 45',
'23 Maths 2 52',
'23 Maths 3 57',
'22 English 51',
'26 Data Structures 72',
'23 Data Structures 63',
'26 English 81'
];
function parseLine(lineStr){
var result = {};
result.studenId = lineStr.split(' ')[0];
var lastSpaceIndex = lineStr.lastIndexOf(' ');
result.subject = lineStr.substring(result.studenId.length+1, lastSpaceIndex);
result.marks = parseInt(lineStr.substring(lastSpaceIndex+1), 10);
return result;
}
function doIt(f){
var avg = [];
for (var i=0; i < f.length; i++){
var lineObj = parseLine(f[i]);
if (lineObj.subject === 'Data Structures'){
avg.push(lineObj.marks);
}
}
return avg.reduce(function(a, b){
return a + b;
},0) / avg.length;
}
console.log(doIt(f));
What about regexp? (C#)
public class Question
{
private const string default_journal_file = "../../journal.txt";
private const string subject_for_acceptance_test = "Data Structures";
private List<StudentInfo> students;
public string journal_file { get; private set; }
public string subject { get; set; }
/**
* Struct with description of information about the student
*/
private struct StudentInfo {
public int StudentID;
public string Subject;
public int Mark;
public StudentInfo(int student_id, string subject, int mark) {
StudentID = student_id;
Subject = subject;
Mark = mark;
}
}
public Question (string subject_name)
{
subject = subject_name;
journal_file = default_journal_file;
students = new List<StudentInfo> ();
ReadJournal ();
}
public Question (string subject_name, string journal_file_path)
{
subject = subject_name;
journal_file = journal_file_path;
students = new List<StudentInfo> ();
ReadJournal ();
}
public int AverageMark() {
int sum_of_marks = 0;
int marks_count = 0;
foreach (StudentInfo student_info in students) {
if (student_info.Subject == subject) {
sum_of_marks += student_info.Mark;
marks_count++;
}
}
return sum_of_marks / marks_count;
}
private void ReadJournal() {
using (StreamReader sr = new StreamReader (journal_file)) {
Regex rgx = new Regex (@"^(\d+)\s(.+)\s(\d+)$");
while (!sr.EndOfStream) {
string current_line = sr.ReadLine ();
if (rgx.IsMatch(current_line.Trim())) {
Match m = rgx.Match (current_line.Trim());
students.Add (new StudentInfo (int.Parse (m.Groups [1].Value), m.Groups[2].Value.Trim(), int.Parse(m.Groups[3].Value)));
}
}
}
}
}
string source = @"22 Data Structures 45
23 Maths 2 52
23 Maths 3 57
22 English 51
26 Data Structures 72
23 Data Structures 63
26 English 81";
string[] mainArr = source.Split('\n');
string[] subArr;
int count = 0, total = 0;
foreach(string st in mainArr)
{
if (st.Contains("Data Structures"))
{
subArr = st.Split(' ');
count = count + 1;
if (subArr != null && subArr.Length >= 3)
total = total + (Convert.ToInt32(subArr[3].ToString()));
}
}
Console.WriteLine("Count : {0}, Total ; {1}", count,total);
Console.Read();
This solution is going to work if the marks are out of 100.
- Automator July 29, 2014