tags:

views:

98

answers:

3

I am a bit stuck here and can't think further.

public struct CandidateDetail
    {
        public int CellX { get; set; }
        public int CellY { get; set; }
        public int CellId { get; set; }           
    }

var dic = new Dictionary<int, List<CandidateDetail>>();

How can I compare each CandidateDetail item against other CandidateDetail items within the same dictionary in the most efficient way?

Example: There are three keys for the dictionary: 5, 6 and 1. Therefore we have three entries. now each of these key entries would have a List associated with. In this case let say each of these three numbers has exactly two CandidateDetails items within the list associated to each key. This means in other words we have two 5, two 6 and two 1 in different or in the same cells. I would like to know:

if[5].1stItem.CellId == [6].1stItem.CellId => we got a hit. That means we have a 5 and a 6 within the same Cell if[5].2ndItem.CellId == [6].2ndItem.CellId => perfect. We found out that the other 5 and 6 are together within a different cell. if[1].1stItem.CellId == ...

Now I need to check the 1 also against the other 5 and 6 to see if the one exists within the previous same two cells or not.

Could a Linq expression help perhaps? I am quite stuck here... I don't know...Maybe I am taking the wrong approach. I am trying to solve the "Hidden pair" of the game Sudoku. :)

http://www.sudokusolver.eu/ExplainSolveMethodD.aspx

Many Thanks, Kave

A: 

http://stackoverflow.com/questions/2828612/process-every-pair-in-a-sequence/2832625#2832625 shows how you can process every pair within a list

Hightechrider
A: 
from kvp1 in dic
from i1 in Enumerable.Range(0, kvp1.Value.Count)
let candidate1 = kvp1.Value[i2]
from kvp2 in dic
where kvp2.Key >= kvp1.Key
from i2 in Enumerable.Range(0, kvp2.Value.Count)
let candidate2 = kvp2.Value[i2]
where kvp1.Key != kvp2.Key || i2 > i1
where candidate1.CellId == candidate2.CellId
select new { 
  Key1 = kvp1.Key,
  Key2 = kvp2.Key,
  Candidate1 = candidate1,
  Candidate2 = candidate2
}

You may want to modify the select clause for only the information you want or add another where clause if you want only matching candidates from different keys.

svick
This selects each pair twice (c1, c2) and (c2, c1) and selects pairs where Candidate1 and Candidate2 are the same object (c1, c1).
Hightechrider
Yeah, you're right. I changed the code, but it makes it much less readable.
svick
Hi, I appreciate the responses. Are you sure the third line is correct? let candidate1 = kvp1.Value[i2] Shouldn't it be rather [i1]? Otherwise it doesnt compile. But still I dont get any result back once all this code is stored within a var test enumerable. Doesnt seem to find anything. But I must admit I am fairly new to Linq.
Kave
The link I posted shows a simpler way to handle the diagonal matrix generation that is needed here.
Hightechrider