How to precalculate valid number of combinations instead of using while loop?

后端 未结 2 763
执念已碎
执念已碎 2021-01-28 11:12

Given List of datacenters which are dc1, dc2, dc3 and list of machines, h1, h2, h3, h4 as mentioned below -

Datacenters = dc1, dc2, dc3
Machines = h1, h2, h3, h         


        
2条回答
  •  执笔经年
    2021-01-28 11:35

    Not really sure what you've asked here, but i think i can see where the problem is, each time get call get mapping you only generate 1 row. so i've rewritten the code so it generates all of them and gives you back a list of the maps. so you can do what you need with them.

    public class DataCenterMapping {
    
        public static void main(String[] args) {
    
            DatacenterMachineMapping dcm = new DatacenterMachineMapping(
                    Arrays.asList("dc1", "dc2", "dc3"), Arrays.asList("h1", "h2",
                            "h3", "h4"));
    
    
                List> coloHost = dcm
                        .getDatacenterMachineMappings();
    
                System.out.println(coloHost);
    
        }
    }
    
    class DatacenterMachineMapping {
    
        private boolean firstCall = true;
        private int hostListIndex = 0;
        private List datacenterList, hostList;
    
        public DatacenterMachineMapping(List datacenterList,
                List hostList) {
            this.datacenterList = datacenterList;
            this.hostList = hostList;
        }
    
        public List> getDatacenterMachineMappings() {
            List> grid = new ArrayList>();
            for (int i = 0; i < datacenterList.size(); i++) {
    
                Map datacenterMachineMapping = new HashMap();
                String[] line = new String[hostList.size()];
                for (int j = 0; j < line.length; j++) {
                    int off = j + i;
                    if (off >= datacenterList.size()) {
                        off -= datacenterList.size();
                    }
                    datacenterMachineMapping.put(hostList.get(j) ,datacenterList.get(off));
                }
    
                grid.add(datacenterMachineMapping);
            }
            return grid;
        }
    
    }
    

    example output:

    [{h4=dc1, h1=dc1, h3=dc3, h2=dc2}, {h4=dc2, h1=dc2, h3=dc1, h2=dc3}, {h4=dc3, h1=dc3, h3=dc2, h2=dc1}]
    

提交回复
热议问题