鑑於數據中心這是DC1,DC2,DC3和機器,H1,H2,H3,H4的名單列表 -如何預先計算有效數量的組合而不是使用while循環?下面所提到
Datacenters = dc1, dc2, dc3
Machines = h1, h2, h3, h4
我想生成以下唯一組合 -
a) {dc1=h1, dc3=h3, dc2=h2}
b) {dc1=h2, dc3=h4, dc2=h3}
c) {dc1=h3, dc3=h1, dc2=h4}
d) {dc1=h4, dc3=h2, dc2=h1}
每個通道中的每個數據中心都應該獲得備用機器/主機。他們不應該得到相同的機器。例如在a
中,如上所示 - dc1 gets h1
,dc2 gets h2
,dc3 gets h3
所以所有機器對於每個數據中心都不相同。並且在b
- 現在爲dc1 gets h2
(因爲dc1已經在第一階段中已經獲得h1)中顯示的第二階段中,dc2 got h3
(bcoz dc2在第一階段中已經獲得了h2)以及dc3 got h4
(bcoz dc3在第一階段中已經獲得了h3)和等等等等
而且一個例子 - 如果我只有三個主機,然後在下面結合我應該得到的只有 -
Datacenters = dc1, dc2, dc3
Machines = h1, h2, h3
{dc1=h1, dc3=h3, dc2=h2}
{dc1=h2, dc3=h1, dc2=h3}
{dc1=h3, dc3=h2, dc2=h1}
於是我想出了下面的代碼工作完全正常 -
public class DataCenterMapping {
public static void main(String[] args) {
DatacenterMachineMapping dcm = new DatacenterMachineMapping(Arrays.asList("dc1", "dc2", "dc3"), Arrays.asList(
"h1", "h2", "h3", "h4"));
// is there any way to avoid while loop here?
while (true) {
Map<String, String> coloHost = dcm.getDatacenterMachineMapping();
System.out.println(coloHost);
for (Map.Entry<String, String> entry : coloHost.entrySet()) {
}
}
}
}
class DatacenterMachineMapping {
private boolean firstCall = true;
private int hostListIndex = 0;
private List<String> datacenterList, hostList;
private Map<String, Set<String>> dataCenterHostsMap = new HashMap<String, Set<String>>();
public DatacenterMachineMapping(List<String> datacenterList, List<String> hostList) {
this.datacenterList = datacenterList;
this.hostList = hostList;
}
public Map<String, String> getDatacenterMachineMapping() {
Map<String, String> datacenterMachineMapping = new HashMap<String, String>();
if (!firstCall) {
if (hostListIndex <= 0) {
hostListIndex = hostList.size();
}
hostListIndex--;
} else {
firstCall = false;
}
for (String datacenter : datacenterList) {
if (hostListIndex == hostList.size()) {
hostListIndex = 0;
}
if (addDataCenterHost(datacenter, hostList.get(hostListIndex))) {
datacenterMachineMapping.put(datacenter, hostList.get(hostListIndex++));
}
}
hostListIndex--;
return datacenterMachineMapping;
}
private boolean addDataCenterHost(String datacenter, String host) {
Set<String> dataCenterHostSet = dataCenterHostsMap.get(datacenter);
if (dataCenterHostSet == null) {
dataCenterHostSet = new HashSet<String>();
dataCenterHostsMap.put(datacenter, dataCenterHostSet);
}
return dataCenterHostSet.add(host);
}
}
問題陳述: -
唯一的問題是我有一個while循環,這將繼續始終運行,
有什麼辦法,我可以預先計算使用while循環有效組合的數量,而不是?
有效組合數= Max(Datacenters_Count,Machines_Count) – MBo