I have a List<List<int>>
set of data, with string representation like this (to give the idea!):
{{1,3},{-1,-3},{2,5},{-2,-5},{-3,4},{-5,4},{3,5,-4},{6,-8},{7,-8},{-6,-7,8},{7,9},{-7,-9},{3,8,-10},{-3,-8,-10},{-3,8,10},{3,-8,10},{4,9,-11},{-4,-9,-11},{-4,9,11},{4,-9,11},{10,11},{-1,6},{1,-6},{-2,7},{2,-7}}
I want to check if ,in all present numbers, exist a number or set of numbers which only are in positive form. I mean if in the whole data, there is 3 and -3 I should return false, otherwise I have to add 3 as a number which only is present as positive 3, in to another list. (Same thing for only negative number)
Here is how I am trying to do it:
First, generate a unique set of numbers and remove negatives:
private void GenerateCurrentExistingVariables()
{
_uid = new List<int>();
var all = _cnf.Data.SelectMany(list => list).ToList();
_uid = all.Distinct().ToList(); //make list unique
_uid.Sort(); //sort numbers
_uid.Reverse(); //reverse so highest numbers would evalaute first!
_uid = _uid.Where(i => i >= 0).ToList(); //remove negative numbers
}
Then I do something like this:
in a method, I call the code below:
for (var i = 0; i < _uid.Count; i++)
{
if (ExistOnlyInNegatedForm(_uid[i]))
{
onlyNegatedList.Add(_uid[i]);
}
if (ExistOnlyInPositiveForm(_uid[i]))
{
onlyPositiveList.Add(_uid[i]);
}
}
Which in turns calls the methods below:
private bool ExistOnlyInPositiveForm(int id)
{
for (var i = 0; i < _cnf.Data.Count; i++)
{
for (var j = 0; j < _cnf.Data[i].Count; j++)
{
if (_cnf.Data[i][j] == id)
{
return false;
}
}
}
return true;
}
private bool ExistOnlyInNegatedForm(int id)
{
var toCheck = -id;
for (var i = 0; i < _cnf.Data.Count; i++)
{
for (var j = 0; j < _cnf.Data[i].Count; j++)
{
if (_cnf.Data[i][j] == -toCheck)
{
return false;
}
}
}
return true;
}
This is too much code for this simple task and I feel that this is getting slower and slower when data grows larger...please let me know how can I improve this. Also I would like this to be done using LINQ at least for the sake of less lines of code!
Aucun commentaire:
Enregistrer un commentaire