Hello everyone ,
I want to ensure that when one subregion is connected to another via
linkedSubRegions, and that other subregion is connected to a third one, all three are concatenated into a single group.
for example:
"987" is connected to "Schwerverkehr".
"Schwerverkehr" is connected to "975".
Therefore, "975", "987", and "Schwerverkehr" should be concatenated into one group.
const region1: Region = {
key: 1,
name: 'Nahverkehr',
subRegions: [
{ key: 1, name: '975', linkedSubRegions: [{ key: 25, name: 'Schwerverkehr' }] },
{ key: 2, name: '987', linkedSubRegions: [{ key: 25, name: 'Schwerverkehr' }] },
{ key: 3, name: 'Aschaffenburg', linkedSubRegions: [] },
{ key: 4, name: 'Aschaffenburg-Land', linkedSubRegions: [{ key: 3, name: 'Aschaffenburg' }] },
{ key: 5, name: 'Marktheidenfeld', linkedSubRegions: [{ key: 4, name: 'Aschaffenburg-Land' }] },
{ key: 25, name: 'Schwerverkehr', linkedSubRegions: [] },
],
};
result should be :
subRegions: [
{ key: 1, name: '975,987,Schwerverkehr'},
{ key: 3, name: 'Aschaffenburg,Aschaffenburg-Land,Marktheidenfeld'}
],
What I have tried:
mergeConnectedSubregions(region: Region): SubRegion[] {
const subregionsMap: Map<number, SubRegion> = new Map();
const visited: Set<number> = new Set();
for (const subregion of region.subRegions!) {
subregionsMap.set(subregion.key!, subregion);
}
const mergedSubregions: SubRegion[] = [];
const connectedSubregions: SubRegion[] = [];
for (const subregion of region.subRegions!) {
if (!visited.has(subregion.key!)) {
dfs(subregion);
const mergedNames = connectedSubregions.map(sub => sub.name).join(',');
const mergedSubregion: SubRegion = {
key: -1,
name: mergedNames
};
mergedSubregions.push(mergedSubregion);
}
}
return mergedSubregions;
function dfs(subregion: SubRegion) {
if (visited.has(subregion.key!)) return;
visited.add(subregion.key!);
connectedSubregions.push(subregion);
for (const model of subregion.linkedSubRegions!) {
const connectedSubregion = subregionsMap.get(model.key!);
if (connectedSubregion) {
dfs(connectedSubregion);
}
}
}
}
result was :
[
{
"key": -1,
"name": "975,Schwerverkehr",
},
{
"key": -1,
"name": "975,Schwerverkehr,987",
},
{
"key": -1,
"name": "975,Schwerverkehr,987,Aschaffenburg",
},
{
"key": -1,
"name": "975,Schwerverkehr,987,Aschaffenburg,Aschaffenburg-Land",
},
{
"key": -1,
"name": "975,Schwerverkehr,987,Aschaffenburg,Aschaffenburg-Land,Marktheidenfeld"
}
]