Microsoft Interview Question


Country: India




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

This solution is going to work if the marks are out of 100.

int count = 0;
            int total = 0;
            var allLinesInFile = File.ReadAllLines(@"File.txt");

            for (int i = 0; i < allLinesInFile.Length; i++)
            {
                var currentLine = allLinesInFile[i].Trim(); // remove the extra space at the end of the string
                if (currentLine.Contains("Data Structure"))
                {
                    count++;
                    int length = currentLine.Length;
                    string substring = currentLine.Substring(length - 2); //gets the last two characters
                    int value = 0;
                    bool tryToGetMarks = int.TryParse(substring, out value);
                    if (tryToGetMarks)
                    {
                        Console.WriteLine("Marks in data structures are   " + value);
                        total += value;
                    }
                }

            }

            Console.WriteLine("Count is " + count);
            Console.WriteLine("Total is: " + total);
            Console.WriteLine("Average is: " + total / count);

- Automator July 29, 2014 | Flag Reply
Comment hidden because of low score. Click to expand.
1
of 1 vote

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;

}

- Saubhik Maiti August 02, 2014 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

Approach : create object for each row and use LINQ to do query as if like DB

- Dev July 19, 2014 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

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);

- William Hoskins July 21, 2014 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

One you determine the "Data Structure" row, start reading the mark from the end and terminate reading once you encounter the space.

- vm July 28, 2014 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

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();

}

- Vishal Bansal August 06, 2014 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

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();

}

- vishal.bansal.341 August 06, 2014 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

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;


}

}
}
}

- Sunil August 30, 2014 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

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");
            }
        }
    }

- Rushabh October 18, 2014 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

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));

- Pavel October 30, 2014 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

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)));
                }
            }
        }
    }
}

- Mike L February 10, 2015 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

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();

- Anonymous July 04, 2015 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

need code in python language

- jay January 06, 2018 | 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