public string Get(string input) { List <int> courses = JsonConvert.DeserializeObject <List <int> >(input); CourseNetwork cn; if (!_cache.TryGetValue(CacheKeys.CourseNetwork, out cn)) { // Key Not in cache, so lets create new data. cn = new CourseNetwork(); cn.BuildNetwork(); // Set cache Options var cOptions = new MemoryCacheEntryOptions() // Set the expiration .SetSlidingExpiration(TimeSpan.FromSeconds(CACHE_TIMEOUT)); // Save Data in cache _cache.Set(CacheKeys.CourseNetwork, cn, cOptions); } Dictionary <int, List <CourseNode> > results = new Dictionary <int, List <CourseNode> >(); foreach (int course in courses) { List <CourseNode> temp; if (!results.TryGetValue(course, out temp)) { results.Add(course, cn.FindShortPath(course)); } } return(JsonConvert.SerializeObject(results, Formatting.Indented)); }
//------------------------------------------------------------------------------ // initiates prerequisite network //------------------------------------------------------------------------------ protected void InitNetwork() { string rawpreqs = DBPlugin.ExecuteToString("SELECT p.CourseID, MaxCredit as credits, GroupID, PrerequisiteID, PrerequisiteCourseID " + "FROM Prerequisite as p " + "LEFT JOIN Course as c ON c.CourseID = p.CourseID " + "FOR JSON PATH"); string rawcourses = DBPlugin.ExecuteToString("SELECT CourseID, MaxCredit as credits " + "FROM Course " + "FOR JSON PATH"); //NETWORK BUILD PrerequisiteNetwork = new CourseNetwork(rawcourses, rawpreqs); PrerequisiteNetwork.BuildNetwork(); }
public string Get(int course) { CourseNetwork cn; if (!_cache.TryGetValue(CacheKeys.CourseNetwork, out cn)) { // Key Not in cache, so lets create new data. cn = new CourseNetwork(); cn.BuildNetwork(); // Set cache Options var cOptions = new MemoryCacheEntryOptions() // Set the expiration .SetSlidingExpiration(TimeSpan.FromSeconds(CACHE_TIMEOUT)); // Save Data in cache _cache.Set(CacheKeys.CourseNetwork, cn, cOptions); } List <CourseNode> graph = cn.FindShortPath(course); // Raw Serialized string from CourseNetwork string graphString = JsonConvert.SerializeObject(graph, Formatting.Indented); return(graphString); }
static void Main(string[] args) { #region Mandatory JSON Files (Can be updated with SQL Queries string rawcourses = File.ReadAllText("../../AllCourses.json"); #region ALLCourses SQL query // select CourseID from Course for JSON AUTO #endregion string rawpreqs = File.ReadAllText("../../PrereqNetwork.json"); #region PrereqNetwork SQL Query // select CourseID, GroupID, PrerequisiteID from Prerequisite for JSON AUTO; #endregion #endregion #region Building the CourseNetwork CourseNetwork courses = new CourseNetwork(rawcourses, rawpreqs); courses.BuildNetwork(); #endregion #region Viewing the Entire Course Network courses.ShowNetwork(); #endregion #region Viewing/Accessing Prerequisites List <CourseNode> targetCourse = new List <CourseNode>(); targetCourse = courses.FindShortPath(199); courses.ShowShortList(targetCourse); Console.WriteLine(""); #endregion #region Viewing/Accessing Prerequisites of Prerequisites List <CourseNode> prereq = new List <CourseNode>(); for (int i = 1; i < targetCourse.Count; i++) { for (int j = 0; j < targetCourse[i].prereqs.Count; j++) { Console.WriteLine("Group Path " + i + " Course #" + (j + 1)); prereq = courses.FindShortPath(targetCourse[i].prereqs[j].prerequisiteID); courses.ShowShortList(prereq); } } Console.WriteLine(""); #endregion #region Viewing/Accessing Prerequisites of Prerequisites of Prerequisites List <CourseNode> prereqPreReq = new List <CourseNode>(); for (int i = 1; i < targetCourse.Count; i++) { for (int j = 0; j < targetCourse[i].prereqs.Count; j++) { Console.WriteLine("Group Path " + i + " Course #" + (j + 1)); prereq = courses.FindShortPath(targetCourse[i].prereqs[j].prerequisiteID); courses.ShowShortList(prereq); for (int x = 1; x < prereq.Count; x++) { for (int y = 0; y < prereq[x].prereqs.Count; y++) { Console.WriteLine("Subgroup Path " + x + " Course #" + (y + 1)); prereqPreReq = courses.FindShortPath(prereq[x].prereqs[y].prerequisiteID); courses.ShowShortList(prereqPreReq); } } Console.WriteLine(""); } } Console.WriteLine(""); #endregion #region Viewing/Accessing Prerequisites of Prerequisites of Prerequisites of Prerequisites List <CourseNode> prereqThird = new List <CourseNode>(); for (int i = 1; i < targetCourse.Count; i++) { for (int j = 0; j < targetCourse[i].prereqs.Count; j++) { Console.WriteLine("Group Path " + i + " Course #" + (j + 1)); prereq = courses.FindShortPath(targetCourse[i].prereqs[j].prerequisiteID); courses.ShowShortList(prereq); for (int x = 1; x < prereq.Count; x++) { for (int y = 0; y < prereq[x].prereqs.Count; y++) { Console.WriteLine("Subgroup Path " + x + " Course #" + (y + 1)); prereqPreReq = courses.FindShortPath(prereq[x].prereqs[y].prerequisiteID); courses.ShowShortList(prereqPreReq); for (int w = 1; w < prereqPreReq.Count; w++) { for (int v = 0; v < prereqPreReq[w].prereqs.Count; v++) { Console.WriteLine("Sub-Subgroup Path " + w + " Course #" + (v + 1)); prereqThird = courses.FindShortPath(prereqPreReq[w].prereqs[v].prerequisiteID); courses.ShowShortList(prereqThird); } } Console.WriteLine(""); } } Console.WriteLine(""); } } Console.WriteLine(""); #endregion #region Review on List<CourseNode> Structure and Accessing/Manipulating Data if (targetCourse != null) { Console.WriteLine("Course Information"); Console.WriteLine("\tCourse ID: " + targetCourse[0].courseID); #region trash attributes Console.WriteLine("\tGroup ID: " + targetCourse[0].groupID); //DO NOT USE (JUNK!) Console.WriteLine("\tPrerequisite ID: " + targetCourse[0].prerequisiteID); //DO NOT USE (JUNK!) if (targetCourse[0].prereqs == null) //DO NOT USE INVALID GROUP ID (JUNK!) { Console.WriteLine("\tPrereqs List is Empty"); } Console.WriteLine(""); #endregion #region Accesing Information by Group ID if (targetCourse.Count > 1) { for (int i = 1; i < targetCourse.Count; i++) //i is Group ID { #region information per Group Index Console.WriteLine("Course ID: " + targetCourse[i].courseID); //usable for error checking Console.WriteLine("Group ID: " + targetCourse[i].groupID); //IDENTIFIES CURRENT GROUP Console.WriteLine("Prerequisite ID: " + targetCourse[i].prerequisiteID); //DO NOT USE (JUNK!) #endregion #region Prerequisite Information for Each Group if (targetCourse[i].prereqs != null) { for (int j = 0; j < targetCourse[i].prereqs.Count; j++) { #region Prerequisite Data Console.WriteLine("\tCourse ID: " + targetCourse[i].prereqs[j].courseID); //usable for error checking Console.WriteLine("\tGroup ID: " + targetCourse[i].prereqs[j].groupID); //usable for path checking Console.WriteLine("\tPrerequisite ID: " + targetCourse[i].prereqs[j].prerequisiteID); //Prerequisite ID #endregion #region Notes on Prerequisites of Prerequisites if (targetCourse[i].prereqs[j].prereqs == null) { Console.WriteLine("\tPrereqs List is Empty"); //Intentionally left blank #region On Manipulation of Structure for Prerequisites of Prerequisites //NOTE: If found necessary, can be used to store the prerequisites of the prerequisites, in which case // this structure would then go a second level. // See Above in "Viewing/Accessing Prerequsites of Prerequisites" for Structure Creation/Access // More Specifically, the function call below: // targetCourse[i].prereqs[j].prereqs = courses.FindShortPath(targetCourse[i].prereqs[j].prerequisiteID) // Would allow for the assignment of the prerequisites of the prerequisites to the original // prerequisite string. // // Also, Since the FindShortPath is an O(N) operation each level of prerequisites added to the structure // is an additional O(N) process. Assigning the prerequisites of the prerequsites is therefore an // O(N^2) operation. Going further to assigning the prerequisites of the prerequisites of the // prerequisites increases the complexity to O(N^3) operation. And So on and so on. #endregion } #endregion Console.WriteLine(""); } } #endregion Console.WriteLine(""); } #endregion } } #endregion Console.ReadLine(); //Used like a System("Pause") to allow review of Console Output }
private void button2_Click() { profBS.MoveFirst(); var net = new CourseNetwork(); var professors = new Professor[profBS.Count]; profBS.MoveFirst(); int UnassignedIndex = -1; while (true) { int m = ((Profs)(profBS.Current)).NoOfCourses; string s = ((Profs)(profBS.Current)).ProfName; professors[profBS.Position] = new Professor(net, m, s); if (((Profs)profBS.Current).UnassignedProf) { UnassignedIndex = profBS.Position; } if (profBS.Position == profBS.Count - 1) { break; } profBS.MoveNext(); } //----------------- courseBS.MoveFirst(); var course = new IntVariable[courseBS.Count]; int noOfCourses = courseBS.Count; var TimeSlots = new int[courseBS.Count][]; var DOW = new string[courseBS.Count]; int max = net.Professors.Count - 1; for (int i = 0; i < courseBS.Count; i++) { string cName = ((Course)(courseBS.Current)).CourseName; course[i] = new IntVariable(net, 0, max, cName); TimeSlots[i] = ParseTimeSlot(((Course)(courseBS.Current)).TimeSlot); DOW[i] = ((Course)(courseBS.Current)).DaysOfWeek; if (((Course)(courseBS.Current)).ProfID != null) { int c = 0; for (int j = 0; j < profBS.Count; j++) { var pf = (Profs)profBS[j]; if (pf.ProfID == ((Course)(courseBS.Current)).ProfID.Value) { c = pf.RowID - 1; break; } } course[i].Equals(c); } courseBS.MoveNext(); } ///////////////////////// /// ///////////////// /// /////////////// /// //course[1].equals(14); course[1].Equals(15, ConstraintTypes.Soft, 70); course[1].Equals(17, ConstraintTypes.Soft, 100); course[0].Equals(17, ConstraintTypes.Soft, 90); course[2].Equals(3, ConstraintTypes.Soft, 50); CreateNotEqualConstraint(courseBS.Count, DOW, TimeSlots, course); new Count(net, course); //Professor dummyPorf = professors[net.Professors.Count - 1]; //dummyPorf.Courses = 0; // always initialize with 0 int sum = 0; if (net.Professors != null) { foreach (Professor p in net.Professors) { sum += p.Courses; } } bool OK = true; int overAllAVG = sum / (net.Professors.Count - 1); if (sum < noOfCourses) { if (UnassignedIndex > -1) { professors[UnassignedIndex].Courses = noOfCourses - sum; } else { MessageBox.Show( "Number of courses is more than the professors' courses..\nYou should assign Unassigned professor!"); OK = false; } } else if (checkBox1.Checked) { if (sum > noOfCourses) // must distribute evenly { int sumOver = 0; int c = 0; foreach (Professor p in net.Professors) { if (p.Courses > overAllAVG) { sumOver += p.Courses; c++; } } int avg = 0; if (c > 0) { avg = sumOver / (c - 1); } foreach (Professor p in net.Professors) { if (p.Courses > avg) { p.Courses = avg; } } int sumAfter = 0; foreach (Professor f in net.Professors) { sumAfter += f.Courses; } int diff = noOfCourses - sumAfter; if (diff > 0) { while (diff > 0) { foreach (Professor g in net.Professors) { if (diff <= 0) { break; } if (g.RealNoOfCourses > avg) { g.Courses++; diff--; } } } } else if (diff < 0) { while (diff < 0) { foreach (Professor g in net.Professors) { if (diff >= 0) { break; } if (g.RealNoOfCourses > avg) { g.Courses--; diff++; } } } } } } if (OK) { Solve(net, course, noOfCourses); } }
private void button1_Click() { var net = new CourseNetwork(); string fileName = SelectTextFile("."); if (fileName != null) { //---------------------- // Prof reading StreamReader re = File.OpenText(fileName); string input = re.ReadLine(); int n; try { n = Convert.ToInt16(input); } catch (Exception) { Console.WriteLine("Failed to read no of prof "); return; } var professors = new Professor[n]; for (int i = 0; i < n; i++) { input = re.ReadLine(); int m; string[] s = input.Split(';'); try { m = Convert.ToInt16(s[1]); // no of events } catch { Console.WriteLine("Failed to read no of courses per prof " + s[0]); return; } professors[i] = new Professor(net, m, s[0]); } //----------------------- // course reading input = re.ReadLine(); try { n = Convert.ToInt16(input); } catch (Exception) { Console.WriteLine("Failed to read no of courses "); return; } var course = new IntVariable[n]; int noOfCourses = n; var TimeSlots = new int[n][]; var DOW = new string[n]; int max = net.Professors.Count - 1; for (int i = 0; i < n; i++) { input = re.ReadLine(); string[] s = input.Split(' '); string cName = s[0]; // no of events course[i] = new IntVariable(net, 0, max, cName); TimeSlots[i] = ParseTimeSlot(s[1]); DOW[i] = s[2]; } CreateNotEqualConstraint(n, DOW, TimeSlots, course); ///----------------- /// input = re.ReadLine(); try { n = Convert.ToInt16(input); } catch (Exception) { Console.WriteLine("Failed to read no of equal constraints "); return; } try { for (int i = 0; i < n; i++) { input = re.ReadLine(); string[] s = input.Split(' '); int ProfIndex = Convert.ToInt16(s[0]); int CourseIndex = Convert.ToInt16(s[1]); course[CourseIndex].Equals(ProfIndex); } } catch (Exception) { Console.WriteLine("Error in reading equal constraint "); return; } re.Close(); Professor dummyPorf = professors[net.Professors.Count - 1]; dummyPorf.Courses = 0; // always initialize with 0 new Count(net, course); int sum = 0; if (net.Professors != null) { foreach (Professor p in net.Professors) { sum += p.Courses; } } int overAllAVG = sum / (net.Professors.Count - 1); if (sum < noOfCourses) { dummyPorf.Courses = noOfCourses - sum; } else if (checkBox1.Checked) { if (sum > noOfCourses) // must distribute evenly { int sumOver = 0; int c = 0; foreach (Professor p in net.Professors) { if (p.Courses > overAllAVG) { sumOver += p.Courses; c++; } } int avg = 0; if (c > 0) { avg = sumOver / (c - 1); } foreach (Professor p in net.Professors) { if (p.Courses >= avg) { p.Courses = avg; } } int sumAfter = 0; foreach (Professor f in net.Professors) { sumAfter += f.Courses; } int diff = noOfCourses - sumAfter; if (diff > 0) { while (diff > 0) { foreach (Professor g in net.Professors) { if (diff <= 0) { break; } if (g.RealNoOfCourses > avg) { g.Courses++; diff--; } } } } else if (diff < 0) { while (diff < 0) { foreach (Professor g in net.Professors) { if (diff >= 0) { break; } if (g.RealNoOfCourses > avg) { g.Courses--; diff++; } } } } } } Solve(net, course, noOfCourses); } }
/// <summary> /// /// </summary> /// <param name="net"></param> /// <param name="course"></param> /// <param name="noOfCourses"></param> private void Solve(CourseNetwork net, IntVariable[] course, int noOfCourses) { //net.Objective = course[0]; Solver solver; if (radioButton6.Checked) { solver = new IterativeBranchAndBoundSearch(net, Solver.Minimize); } else if (radioButton4.Checked) { solver = new DefaultSolver(net, Solver.Minimize); solver.SolverStrategy = (Solver.StrategyMethod)numericUpDown3.Value; } else if (radioButton3.Checked) { //int opt = Solver.BETTER; solver = new TabooSearch(net, Solver.Minimize); } else { net.Objective = course[0]; solver = new SimulatedAnneallingSearch(net, Solver.Minimize); } long timer = DateTime.Now.Ticks; int count = 1; //StreamWriter sw = new StreamWriter(".\\out.txt"); DBSolution.DeleteAll(); Notes = new IList[(int)numericUpDown1.Value]; Solution bestSolution = null; for (solver.Start((long)numericUpDown2.Value); solver.WaitNext(); solver.Resume()) { Solution sol = solver.Solution; if (count == 1) { bestSolution = sol; } else { if (bestSolution != null) { if (sol.Weight > bestSolution.Weight) { bestSolution = sol; } } } Notes[count - 1] = new ArrayList { "Weight= " + sol.Weight + "\n" }; for (int i = 0; i < net.Professors.Count; i++) { int pcount = 0; for (int j = 0; j < net.Variables.Count; j++) { if (!((Variable)net.Variables[j]).IsValueType) { if (sol.GetIntValue(((Variable)net.Variables[j])) == i) { pcount++; } } } if (pcount < ((Professor)net.Professors[i]).RealNoOfCourses) { Notes[count - 1].Add("Prof. " + ((Professor)net.Professors[i]).ToString() + " not consistent.. needs " + (((Professor)net.Professors[i]).RealNoOfCourses - pcount) + " assignment(s) more!!" + "\n"); // sw.WriteLine("Prof. " + ((Professor)net.Professors[i]).toString() + " not consistent.. needs " + // (((Professor)net.Professors[i]).Courses - pcount) + " assignment(s) more!!"); } } Console.Out.WriteLine(); for (int i = 0; i < noOfCourses; i++) { //if (!((Variable)(net.Variables[i])).IsValueType) //{ //sw.WriteLine(course[i].Name + " = " + ((Professor)net.Professors[sol.getIntValue(course[i])]).Name); var dbSolution = new DBSolution { SolutionID = count, CourseName = course[i].Name, ProfessorName = ((Professor)net.Professors[sol.GetIntValue(course[i])]).Name }; dbSolution.AddSolution(); //} } //sw.WriteLine("================================="); count++; //if (solver is DefaultSolver) //{ if (count == numericUpDown1.Value + 1) { break; } //} //else //{ // break; //} } Console.WriteLine(bestSolution); timer = DateTime.Now.Ticks - timer; //sw.WriteLine("timer: " + timer); //sw.WriteLine("Count=" + count); //sw.Close(); solutionBS = new BindingSource(); if (count > 1) { solutionBS.DataSource = DBSolution.GetByID(1); bindingNavigator1.BindingSource = solutionBS; solutionViewGrid.DataSource = solutionBS; solIndex = 1; firstSol.Enabled = false; prevSol.Enabled = false; SolUpDown.Minimum = 1; SolUpDown.Maximum = count - 1; SolUpDown.Value = 1; SolUpDown.Enabled = true; if (count == 2) { nextSol.Enabled = false; lastSol.Enabled = false; } else { nextSol.Enabled = true; lastSol.Enabled = true; } } else { SolUpDown.Minimum = 0; SolUpDown.Maximum = 0; SolUpDown.Enabled = false; firstSol.Enabled = false; prevSol.Enabled = false; nextSol.Enabled = false; lastSol.Enabled = false; } label2.Text = ""; if (count > 1) { for (int y = 0; y < Notes[solIndex - 1].Count; y++) { label2.Text += Convert.ToString(Notes[solIndex - 1][y]); } } numberOfSolutions = count - 1; solutionViewGrid.Columns[2].Visible = false; if (timer / 10000 / 1000 == 0) { MessageBox.Show((count - 1) + " Solution(s) found in " + timer / 1000.0 + " MS"); } else { MessageBox.Show((count - 1) + " Solution(s) found in " + timer / 10000.0 / 1000 + " second(s)"); } }
static void Main(string[] args) { CourseNetwork net = new CourseNetwork(); StreamReader re = File.OpenText("courses.txt");//"Anum1.txt");//"fn1.txt"); //"numfile.txt"); string input = re.ReadLine(); int n; try { n = Convert.ToInt16(input); } catch (Exception) { Console.WriteLine("Failed to read no of profs "); return; } Professor[] professors = new Professor[n]; for (int i = 0; i < n; i++) { input = re.ReadLine(); int m; string[] s = input.Split(' '); try { m = Convert.ToInt16(s[1]); // no of events } catch { Console.WriteLine("Failed to read no of courses per prof " + s[0]); return; } professors[i] = new Professor(net, m, s[0]); } IntVariable[] course = new IntVariable[6]; int max = net.Professors.Count - 1; course[0] = new IntVariable(net, 0, max, "CS110"); course[1] = new IntVariable(net, 0, max, "CS200"); course[2] = new IntVariable(net, 0, max, "CS420"); course[3] = new IntVariable(net, 0, max, "CS310"); course[4] = new IntVariable(net, 0, max, "MA200"); course[5] = new IntVariable(net, 0, max, "ST101"); course[0].NotEquals(course[1]); course[2].NotEquals(course[3]); course[4].NotEquals(course[5]); course[4].Equals(1); re.Close(); Professor dummyPorf = professors[net.Professors.Count - 1]; dummyPorf.Courses = 0; // always initialize with 0 Count cc = new Count(net, course); int sum = 0; if (net.Professors != null) { foreach (Professor p in net.Professors) { sum += p.Courses; } } if (sum < net.Variables.Count) { dummyPorf.Courses = net.Variables.Count - sum; } //net.Objective = course[5]; //int opt = Solver.BETTER; Solver solver = new DefaultSolver(net); long timer = DateTime.Now.Ticks; int count = 0; for (solver.Start(); solver.WaitNext(); solver.Resume()) { Solution sol = solver.Solution; for (int i = 0; i < net.Professors.Count; i++) { int pcount = 0; foreach (Variable v in net.Variables) { if (sol.GetIntValue(v) == i) { pcount++; } } if (pcount < ((Professor)net.Professors[i]).Courses) { Console.WriteLine("Prof. " + ((Professor)net.Professors[i]).ToString() + " not consistent.. needs " + (((Professor)net.Professors[i]).Courses - pcount) + " assignment(s) more!!"); } } Console.Out.WriteLine(); foreach (Variable v in net.Variables) { Console.Out.WriteLine(v.Name + " = " + ((Professor)net.Professors[sol.GetIntValue(v)]).Name); } Console.Out.WriteLine("================================="); count++; } timer = DateTime.Now.Ticks - timer; Console.Out.WriteLine("timer: " + timer); Console.WriteLine("Count=" + count); Console.ReadLine(); }