Faster and less cheesy matching of items from 2 collections - collections

Hi I need to iterate two collections containing different object types and do some matching, adding matched items to a 3rd list.
private CheesyMatch( BindingList< MyTypeA > theListA, BindingList< MyTypeB > theListB )
{
foreach( MyTypeA item in theListA )
{
foreach( MyTypeB item2 in theListB )
{
if( item.name == item2.name )
{
item.matched = true;
item2.matched = true;
MyMatchedList.items.add( new matchedItem( item, item2 ) );
}
}
}
}
Is there a better/more efficient way to do this? (I have simplified things a little, as I have some code in my code that copies to new local collections before iterating them, as I was having threading issues.

Not sure what language this is, but there must be some method liked "exists" or "contains" where you do two loops in series. In pseudo code
foreach item in ListA
if ListB.exists(item) then
MatchedList.items.add(item)
end if
endfor
foreach item in ListB
if ListA.exists(item) then
MatchedList.items.add(item)
end if
endfor
That way you only go over each collection once rather than doing ListB N times where ListA has N items. Does this make sense?

Related

For Each Loop With If Statement - Performance

I am having a complex object, and I am trying to loop through the objects and add to an another list.
But as I have few if statements inside the loop to check whether the object inside is null OR not, the iteration is taking lot of time. Also I am looping through around 70000 items.
Below is the code,
var Product = model; //complex object
Parallel.ForEach({model, product => {
if(product.Type != null)//type a
{ A = a.Loca;//do something }
if(product.Type != null)//type b
{ B = b.Loca;//do something }
if(product.Type != null)//type c
{ A = c.Loca;//do something }
dataAsset.Push(new assetItems(A, B, C));
}
});
I am trying to improve the performance.
Improve the performance by only checking if product.Type != null once. You do not need to check it three separate times. i.e.
Parallel.ForEach({model, product => {
if(product.Type != null)
{ a;//do something
b;//do something
c;//do something
}
dataAsset.Push(new assetItems(a, b, c));
}
By using Elvis operator I was able to improve the performance.

Doctrine ORM many-to-many find all by taglist

I'v got simple m2m relation (book -> book_mark <- mark). I want to find item(book) by 1-2-3... x-count of tags(marks). Example: Book1 got these tags: [Mark1, Mark2, Mark3], Book2 got these tags: [Mark1, Mark3, Mark4]. Search list is [Mark1, Mark2]. I want to find only items, which have ALL tags from Search list, i.e. only Book1 in this example.
I have tried many ways and spend much time google it, but didn't find the answer.
Closest that I have is this:
return $this->createQueryBuilder('b')
->select('b, m')
->leftJoin('b.marks_list', 'm')
->andWhere(':marks_list MEMBER OF b.marks_list')
->setParameter('marks_list', $marksList)
->getQuery()->getArrayResult();
But it's looking for books which have at least 1of the parameters, not all of them together
Next, I'v decided that I'm absolutely wrong and start thinking this way:
public function findAllByMarksList(array $marksList)
{
$qb = $this->createQueryBuilder('b')
->select('b, m')
->leftJoin('b.marks_list', 'm');
for ($i = 0; $i<count($marksList); $i++){
$qb->andWhere('m.id in (:mark'.$i.')')
->setParameter('mark'.$i, $marksList[$i]);
}
return $qb->getQuery()->getArrayResult();
}
But here I faced another problem: This code is checking only 1 mark and then always returns an empty set if the number of parameters is more than 1.
Best regards.
So, updated answer... It works (I have relation many to many between reviews and brands) it's the same situation, but for example if you have
Book 1 - mark1, mark2, mark3
Book 2 - mark1, mark2, mark3, mark4
with this code you will also find the book2, because all of it marks are in this list.
If you need to find book which haves only these 3 tags, you additionally need to add checking for count. (Count of tags = count of tagList)
public function test()
{
// just selecting for list for test
$brandsList = $this->_em->createQueryBuilder()
->select('b')
->from('ReviewsAdminBundle:Brands', 'b')
->where('b.id in (:brandIds)')
->setParameter('brandIds', [6,4])
->getQuery()
->getResult();
dump($brandsList);
// query part
$qb = $this->createQueryBuilder('r')
->select('r')
->leftJoin('r.brand', 'brands')
->where('r.published = 1');
foreach ($brandsList as $oneBrand) {
/** #var Brands $oneBrand */
$identifier = $oneBrand->getId();
$qb->andWhere(':brand'.$identifier.' MEMBER OF r.brand')
->setParameter('brand'.$identifier, $identifier);
}
dump($qb->getQuery()->getResult());
die;
}
ps. Additionally you can check doctrine2 queryBuilder must return only result matching with array values (ids): 0/Null and/or One and/or Many id(s) have to return One result (close to our situation)
And, I think there's not better way of accomplishing this. Either you use multiple andWheres to compare id OR use MEMBER OF

Algorithm to Save Items with Parent-Child Relationship to Database

I need help designing the logic of an app that I am working on.
The application should enable users to create mindmaps and save them to a mysql database for later editing.
Each mindmap is made up of inter-related nodes, meaning a node should have a parent node and the id of the mindmap to which it belongs.
I am stuck here. How can I save the nodes to the database and be able to query and rebuild the mindmap tree from the query results.
Root
Child1
Child2
GrandChild1
GreatGrandChild1
GreatGrandChild1
Child3
GrandChild2
I need an algorithm, that can save the nodes and also be able to figure out the relationships/order of items similar to the Tree that I have given. This is very much like how menus are saved and retrieved in Wordpress but I can't find the right logic to do this.
I know there are really great people here. Please help.
This is very easy in a 3 column table.
Column-1: id, Column-2: name, Column-3: parent_id
for example, the data would be like this:
1 ROOT NULL
2 Child1 1
3 Child2 1
... and so on..
I finally found a solution. Here's my full code.
require_once('config.php');//db conn
$connect = mysql_connect(DB_HOST, DB_USER, DB_PASS);
mysql_select_db(DB_NAME);
$nav_query = MYSQL_QUERY("SELECT * FROM `nodes` ORDER BY `id`");
$tree = ""; // Clear the directory tree
$depth = 1; // Child level depth.
$top_level_on = 1; // What top-level category are we on?
$exclude = ARRAY(); // Define the exclusion array
ARRAY_PUSH($exclude, 0); // Put a starting value in it
WHILE ( $nav_row = MYSQL_FETCH_ARRAY($nav_query) )
{
$goOn = 1; // Resets variable to allow us to continue building out the tree.
FOR($x = 0; $x < COUNT($exclude); $x++ ) // Check to see if the new item has been used
{
IF ( $exclude[$x] == $nav_row['id'] )
{
$goOn = 0;
BREAK; // Stop looking b/c we already found that it's in the exclusion list and we can't continue to process this node
}
}
IF ( $goOn == 1 )
{
$tree .= $nav_row['name'] . "<br>"; // Process the main tree node
ARRAY_PUSH($exclude, $nav_row['id']); // Add to the exclusion list
IF ( $nav_row['id'] < 6 )
{ $top_level_on = $nav_row['id']; }
$tree .= build_child($nav_row['id']); // Start the recursive function of building the child tree
}
}
FUNCTION build_child($oldID) // Recursive function to get all of the children...unlimited depth
{
$tempTree='<ul>';
GLOBAL $exclude, $depth; // Refer to the global array defined at the top of this script
$child_query = MYSQL_QUERY("SELECT * FROM `nodes` WHERE parent_id=" . $oldID);
WHILE ( $child = MYSQL_FETCH_ARRAY($child_query) )
{
IF ( $child['id'] != $child['parent_id'] )
{
FOR ( $c=0;$c<$depth;$c++ ) // Indent over so that there is distinction between levels
{ $tempTree .= " "; }
$tempTree .= "<li>" . $child['name'] . "</li>";
$depth++; // Incriment depth b/c we're building this child's child tree (complicated yet???)
$tempTree .= build_child($child['id']); // Add to the temporary local tree
$depth--; // Decrement depth b/c we're done building the child's child tree.
ARRAY_PUSH($exclude, $child['id']); // Add the item to the exclusion list
}
}
RETURN $tempTree.'</ul>'; // Return the entire child tree
}
ECHO $tree;
?>
This is based on the piece of code found here http://psoug.org/snippet/PHP-Recursive-function-to-generate-a-parentchild-tree_338.html I hope this helps someone as well

PHP manipulating multiarray data

I have a problem. I don't know how to show the exactly data I want.
My array is like this:
$races[$numRace][$finalPosition]
$races[1][1] = array ('stephan','1:27,895');
$races[1][2] = array ('george', '1:29,075');
$races[1][3] = array ('peter', '1:29,664');
$races[1][4] = array ('benson', '1:29,915');
$races[2][1] = array ('benson', '1:41,113');
$races[2][2] = array ('stephan','1:41,434');
$races[2][3] = array ('george', '1:43,654');
foreach ($races as $v1) {
foreach ($v1 as $v2) {
foreach ($v2 as $v3) {
echo "$v3\n";
}
}
}
This one shows me every data of $race array.
My question is: How can I do for showing just results for race 2?
Important: We don't know how many runners have participated on each race (So, we need a "foreach").
I would like a result like this:
benson
stephan
george
Simply iterate through only the relevant array. Based on your code your foreach should be:
foreach ($races[2] as $pos => $info){
echo $pos.': '.$info[0];
}
I've hard-coded the value 2 in the code but you could easily use a variable (foreach ($races[$raceNum]).
If you don't already know, => makes it possible for us to use both the key and the value as variables in our loop.

Regarding to retrieve values inside the array

Hi
I am creating online quiz in asp.net c#. For that i have one form that displays testlist in dropdownlist & start button. After clicking 2nd form appears, 2nd form shows one label for question, radiobuttonlist for answers ,next & checkbox for review. I am creating array of random question ids in start button click event of the 1stform. when i click next button in 2nd form then next random question appears, i want array of questions those are checked for review. I used code for arrays of values ( eg.10101) 1 for true & 0 for false as follows but i want array of that question ids those are checked:
int[] a = (int[])Session["values"];//this is array of random question ids created in 1st form
int g;
if (chkmark.Checked == true)
{
g = 1;
}
else
{
g = 0;
}
int[] chkarray = new int[Convert.ToInt32(Session["Counter"]) - 1];
int[] temp1 = (int[])Session["arrofchk"];
int k, no;
if (temp1 == null)
no = 0;
else
no = temp.Length;
for (k = 0; k < no; k++)
{
chkarray[k] = temp1[k];
}
chkarray[j] = g;
Personally, i would use a Dictionary<int, bool> for this.
In the key of the dictionary, you can store the random Question ID, in the value of the pair, you can store the checked item state. It might take you more work now to refactor it, but I believe it will save you a lot of time in the end when you want to do more actions on your quiz items.
Using a dictionary - or at least a well chosen collection, I think it will be easier to get the right data back.
For your example, it can work only if the positions of both arrays are the same.
Dictionary<int, bool> quizAnswers = new Dictionary<int, bool>(); // <questionID, checked>
// Fill dictionary with questions and answers
for(int i=0;i<a.length;i++)
{
if(temp1.length > i) // Make sure we don't get an IndexOutOfBoundsException
{
quizAnswers.Add(a[i], temp1[i] == 1);
}
}
// Get Answered question in array ( LINQ )
int[] checkedAnswers = (from KeyValuePair<int, bool> pair in quizAnswers
where pair.Value == true
select pair.Key).ToArray<int>();
The reason I am using a Dictionary here, is because I personally think it's neater than having two separate arrays.
I believe you should implement a Dictionary in your quiz, in stead of those arrays. What if the array indexes don't match, or you want to dynamically add a question to a fixed size array, etc..
It's something to take into consideration. Hope I could help you out.

Resources