-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathInversions.cs
More file actions
69 lines (53 loc) · 2.13 KB
/
Inversions.cs
File metadata and controls
69 lines (53 loc) · 2.13 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
using System;
using System.IO;
using System.Linq;
namespace Algorithms
{
// Download the text file here. (Right click and save link as)
// This file contains all of the 100,000 integers between 1 and 100,000 (inclusive) in some order, with no integer repeated.
// Your task is to compute the number of inversions in the file given, where the ith row of the file indicates the ith entry of an array.
// Because of the large size of this array, you should implement the fast divide-and-conquer algorithm covered in the video lectures.
// The numeric answer for the given input file should be typed in the space below.
// So if your answer is 1198233847, then just type 1198233847 in the space provided without any space / commas / any other punctuation marks.
// You can make up to 5 attempts, and we'll use the best one for grading.
// (We do not require you to submit your code, so feel free to use any programming language you want --- just type the final numeric answer in the following space.)
// [TIP: before submitting, first test the correctness of your program on some small test files or your own devising.
// Then post your best test cases to the discussion forums to help your fellow students!]
public class Inversions
{
public string InputFileName {
get;
set;
}
public int[] Integers {
get;
set;
}
public Inversions (string inputFileName)
{
InputFileName = inputFileName;
if (!File.Exists (InputFileName))
{
throw new FileNotFoundException ();
}
Integers = Array.ConvertAll (File.ReadAllLines (InputFileName), int.Parse);
}
// Main recursive algorithm.
public int GetInversions(int[] integers)
{
if (integers.Length == 1)
{
return 0;
}
int midPoint = integers.Length / 2;
var leftInversions = GetInversions (integers.Take (midPoint).ToArray());
var rightInversions = GetInversions (integers.Skip (midPoint).Take (integers.Length - midPoint).ToArray());
var splitInversions = CountSplitInversions (integers);
return leftInversions + rightInversions + splitInversions;
}
private int CountSplitInversions (int[] integers)
{
return 1;
}
}
}