Reputation: 155
I have written a script in Powershell that searches through a relational database using Select Top statements to pick records which are suitable to match with items in an input text file. For the sake of simplicity I not include all of the condition that need to be met, just the ones I am having trouble with:
Each item in the input file has a corresponding requirement for resource x and resource y.
Input File:
Record 1 2x 1y
Record 2 1x 1y
In the database each record is similar
Database:
Record 1 4x 3y
Record 2 1x 2y
What my script does is loop through each item in my input file and searches through the database to find a record that has sufficient amount of resource x and resource y. The script does this and outputs a file which basically matches records of the input file to suitable records of the database.
However, it doesn't work properly as it step through each item in the loop, it doesn't take into account if the previous item(s) in the loop have been matched to records (and used up resources). For example:
The script evaluates input file record 1 (2x 1y) and matches it to record 1 in the DB (4x 3y). Now when the script goes to the next item in input file (1x 1y) it evaluates record 1 in the DB as still having 4x and 3y despite having been matched previously in the loop and it's resources should now be looked at as 2x 2y (4x-2x 3y-1y).
How can I accomplish this? In the end the script could be evaulating 200 input records at a time against a Database with 70,000 records. The answer doesn't have to be in PowerShell, I'm just having a hard time thinking of a conceptual answer to this problem.
Upvotes: 1
Views: 87
Reputation: 3275
Here's a PowerShell example using randomly generated CSVs.
Input table format:
RecordName ResourceX ResourceY Match
Record 0 8 0
Record 1 2 5
Record 2 5 9
Processing:
$cResources = Import-Csv resources-before.csv
$cResourcesNeeded = Import-Csv needed-infile.csv
foreach ($needed in $cResourcesNeeded) {
foreach ($supply in $cResources) {
if (($needed.ResourceX -le $supply.ResourceX) -and `
($needed.ResourceY -le $supply.ResourceY)) {
# Match found.
$needed.Match = $supply.RecordName
$supply.Match += $needed.RecordName
# Updating supply record.
$supply.ResourceX = $supply.ResourceX - $needed.ResourceX
$supply.ResourceY = $supply.ResourceY - $needed.ResourceY
# Back to outer loop.
break
}
}
}
$cResources | Export-Csv -NoTypeInformation resources-after.csv
$cResourcesNeeded | Export-Csv -NoTypeInformation needed-outfile.csv
Of course this is just a very basic example. I don't know what other requirements you have so feel free to elaborate further (i.e. update the question with your actual code) if you need something more specific.
Upvotes: 1