2016-09-08 3 views
0

"6 선택 2"조작의 변형을 수행하려고합니다. 다음 코드를 작성했습니다."선택"조작의 조합 생성

public void choosePatterns(){ 
    String[] data = {"1", "2", "3", "4", "5", "6"}; 
    String[] originalPattern = new String[15]; 
    int index = 0; 
    for(int i = 0; i < (6-1); i++) 
    { 
     for(int j = i+1; j < 6; j++) 
     { 
      System.out.println(i + "," +j); 
     } 
    } 
} 

내 코드는 "6 choose 2"의 가능한 모든 조합을 생성합니다. 그러나 이것을 변경하고 나머지 모든 숫자를 인쇄하고 싶습니다. 지금까지는 "6 choose 2"의 조합 중 하나가 "3"과 "4"이면 "1", "2", "5", "6"을 인쇄하려고합니다.

나는 이것을 가장 효율적으로 수행하는 방법을 잘 모르겠습니다. 길어지는 길은 "데이터"배열에서 해당 색인을 삭제하고, 간격이 없도록 데이터를 이동 한 다음 배열을 인쇄하는 것입니다. 그러나 더 빠르고 효율적인 방법이 있습니까?

+2

뭔가를이 작은, 당신을 위해, println 메소드 후 다른 루프를 추가 할 수 있습니다 (INT의 K = 0; K <6; 케이 ++) {((K 경우! = i) 및 (k = j)) {... println (... k ...)}}. println이 i 대신 data [i]와 같은 것을 사용해서는 안됩니까? – rcgldr

+0

@rcgldr (+1), 나는 전혀 생각하지 못했습니다. 수락 할 수 있도록 답변으로 게시 해 주시겠습니까? 그리고 네, 그것은 데이터이어야합니다 [i]. 그러나 나는이 경우에 그것이 인쇄 될 때 실제로 차이를 말할 수 없다고 생각한다. –

+0

_ 6에서부터 2_를 선택하면 _6과 거의 같아야합니다. 4_를 선택하십시오. – greybeard

답변

0

여기 방법이 있습니다.

public static void choosePatterns(int total, int toChoose) { 
    List<Integer> indices = IntStream.range(1, toChoose + 1).mapToObj(i -> Integer.valueOf(0)).collect(Collectors.toList()); 
    resetIndex(indices, 0, 1, total); 
    while (true) { 
    System.out.println("chosen: " + indices); 
    System.out.print("not chosen: "); 
    for (int i = 1; i <= total; i++) { 
     if (! indices.contains(Integer.valueOf(i))) { 
     System.out.print(i + " "); 
     } 
    } 
    System.out.println("\n"); 

    if (! incrementIndices(indices, indices.size() - 1, total)) { 
     break; 
    } 
    } 
} 

public static boolean resetIndex(List<Integer> indices, int posn, int value, int total) { 
    if (value <= total) { 
    indices.set(posn, value); 
    return posn == indices.size() - 1 ? true : resetIndex(indices, posn + 1, value + 1, total); 
    } else { 
    return false; 
    } 
} 

public static boolean incrementIndices(List<Integer> indices, int posn, int total) { 
    if (indices.get(posn) < total) { 
    indices.set(posn, indices.get(posn) + 1); 
    } else { 
    int resetPosn = posn; 
    do { 
     if (resetPosn-- == 0) return false; 
    } while (! resetIndex(indices, resetPosn, indices.get(resetPosn) + 1, total)); 
    } 
    return true; 
} 

public static void main(String[] args) throws IOException { 
    choosePatterns(6, 2); 
} 

그것은이 인쇄 :

chosen: [1, 2] 
not chosen: 3 4 5 6 

chosen: [1, 3] 
not chosen: 2 4 5 6 

chosen: [1, 4] 
not chosen: 2 3 5 6 

chosen: [1, 5] 
not chosen: 2 3 4 6 

chosen: [1, 6] 
not chosen: 2 3 4 5 

chosen: [2, 3] 
not chosen: 1 4 5 6 

chosen: [2, 4] 
not chosen: 1 3 5 6 

chosen: [2, 5] 
not chosen: 1 3 4 6 

chosen: [2, 6] 
not chosen: 1 3 4 5 

chosen: [3, 4] 
not chosen: 1 2 5 6 

chosen: [3, 5] 
not chosen: 1 2 4 6 

chosen: [3, 6] 
not chosen: 1 2 4 5 

chosen: [4, 5] 
not chosen: 1 2 3 6 

chosen: [4, 6] 
not chosen: 1 2 3 5 

chosen: [5, 6] 
not chosen: 1 2 3 4 
0

글쎄, [6 choose X]가 동적으로 (X = 2, 3, 4, ..)되도록하고 모든 경우에 대해 for 루프의 특정 숫자를 추가하고 싶지 않으므로 재귀 트릭을해야합니다.

public void choosePatterns(){ 
    String[] data = {"1", "2", "3", "4", "5", "6"}; 
    int deep = 3; // << This value is the X above 
    deep = deep > data.length ? data.length : deep; // << prevent X over data length 
    printCombine(data, new ArrayList<Integer>(), deep); // Main business here 
} 

printCombine 방법 함량 : I가 int 배열을 사용하여 변경 단지 디스플레이 목적의 값에 1을 추가

private void printCombine(final String[] data, final List<Integer> selectedIdxs, final int deep) { 
    if(deep == 1) { // When come to the last combine number, print out 
     StringBuilder sb = new StringBuilder(); 
     for(int i : selectedIdxs) { 
      sb.append(data[i]); 
      sb.append(", "); 
     } 
     String prefixCombine = sb.toString(); 

     for(int i = 0; i < data.length; i++) { 
      if(!selectedIdxs.contains(i)) { 
       System.out.println(new StringBuilder(prefixCombine).append(data[i]).toString()); 
      } 
     } 
    } else { 
     for(int i = 0; i < data.length; i++) { 
      if(!selectedIdxs.contains(i)) { 
       // Mark the selected indices of the combination 
       List<Integer> curSelectedIdx = new ArrayList<Integer>(); 
       curSelectedIdx.addAll(selectedIdxs); 
       curSelectedIdx.add(i); 
       printCombine(data, curSelectedIdx, deep - 1); 
      } 
     } 
    } 
} 
0

:

의 샘플 코드 다음 보자

public static void choosePatterns(){ 
    int[] display = new int[6]; 
    for(int i = 0; i < (6-1); i++) 
    { 
     for(int j = i+1; j < 6; j++) 
     { 
      display[0] = i+1; 
      display[1] = j+1; 
      int x = 2; 
      for(int k = 0; k < 6; k++) 
      { 
       if((k != i) && (k != j)) 
        display[x++] = k+1; 
      } 
      System.out.println(Arrays.toString(display)); 
     } 
    } 
}