algorithm - C# - Looping through pairs and matching -
so i'm stuck on program have series of pairs may or may not able connect form complete path through pairs. need able check if second item in pair can match first item in pair , on until there no pairs left. example, pairs might be:
(1,5)
(2,4)
(3,2)
(5,3)
(4,3)
i need able somehow iterate through pairs , check if can complete path travels through each one, based on if second digit of pair matches first digit of next pair. in example, output be:
(1,5), (5,3), (3,2), (2,4), (4,3)
forming complete match. if match can't formed, need report failure. input based on text file. far i've been able read file streamreader , split pairs based on newline, iterate through , split each pair items based on comma. i'm pretty clueless on how proceed, if has ideas appreciate it.
streamreader sr = new streamreader("inputs.txt"); string line = null; line = sr.readtoend(); var str = line.trim().split('\n'); int length = str.length; int index=1; while (index < length) { var pair = str[index].split(','); var item1 = pair[0]; var item2 = pair[1]; }
first, need strip parenthesis - if present in input file. see string.trim
method that.
the brute force approach:
public class pair { public string first; public string second; } list<pair> pairs = new list<pair>(); (int index = 0; iter < str.length; index++) { var pair = str[index].split(','); pairs.add(new pair(){first = pair[0], second = pair[1]}); } list<pair> ordered = new list<pair>(); ordered.add(pairs[0]); pairs.removeat(0); while (pairs.count > 0) { bool found = false; (int iter = 0; iter < pairs.count; iter++) { if (ordered[ordered.count - 1].second == pairs[iter].first) { ordered.add(pairs[iter]); pairs.removeat(iter); found = true; break; } } if (!found) { <report error> break; } }
error checking left exercise reader.
Comments
Post a Comment