2012-06-15 3 views
0

부분 집합으로리스트의 "이웃"값을 얻을 수 있습니다 :알고리즘은이 같은 텍스트 파일이

A 
B 
C 

을 그리고 각 요소는 다음과 같이 하위 집합이 있습니다

A = { a1, a2, a3 } 
B = { b1, b2 } 
C = { c1, c2, c3 } 

내가 생성 할을 이 :와 집합 크기가 다양 수 :

 
    a1, b1, c1 
    a2, b1, c1 
    a3, b1, c1 
    a1, b2, c1 
    a1, b1, c2 
    a1, b1, c3 

나는 텍스트 파일의 요소 수 (A, B는 C, D, E는 예를 들어,이 수를) 알 수 없습니다.

나는 2 개의 인덱스, 아마 "배열의 위치"와 "배열의 인덱스"를 가진 재귀 함수라고 생각할 수 있지만,이 모든 것을 구현하는 방법을 정말로 모르겠습니다.

같은 입력을 가진 직교 좌표계를 사용하는 함수를 적용하려고했지만 심지어 완전히 실패했습니다. 데카르트 제품을 생성 할 필요가 없습니다.

+2

'a1, b2, c2'와 같은 조합은 어떨까요? 원하지 않는 것은 무엇입니까? – cheeken

+0

이것은 8 개의 출력 만 있기 때문에 이것은 데카르트 곱처럼 보이지 않습니까? 아니면 정말로 생성하고 싶은 것은 데카르트 제품입니까? – nhahtdh

+0

데카르트 제품을 생성 할 필요가 없으며,이 기능을 제 목적에 맞게 적용하려고했습니다 (그리고 내가 말한 것처럼 실패했습니다). 나는 이것들을 원한다 : 배열이 다른 배열을 떠나지 않는지 검사한다 "변하지 않는다"> A가 끝에있을 때, B 배열에서 "pass"하고 B가 끝에있을 때 똑같이한다. 그런 다음 C 배열에서 "pass"하고 수행한다. 같은, 등등 ... @cheeken 불행히도 나는 이런 식으로 조합하고 싶지 않다. ( – HBv6

답변

3
List<List<Integer>> myInput = ... 

for(int i=0; i<myInput.size(); i++){ 
    for (int j=0; j<myInput.get(i).size(); j++){ 
     if (j == 0 && i > 0){ 
      continue; 
     } 
     List<Integer> result = new ArrayList<Integer>(myInput.size()); 
     for(int k=0; k<myInput.size(); k++){ 
      if (k == i){ 
       result.add(myInput.get(k).get(j)); 
      }else{ 
       result.add(myInput.get(k).get(0)); 
      } 
     } 
     System.out.println(result); 
    } 
} 

인덱스가 반복되는 목록 인 모든 목록을 반복합니다.

반복 할 innerList의 크기를 찾고 그 시간을 반복하십시오.

목록이 색인 된 목록이 아니면 목록의 첫 번째 요소를 항상 반복하며,이 경우 반복 목록에서 다음 값을 가져옵니다.

+0

. 건배 –

+0

리스트 리스트가 아니어야합니다. ? – KidTempo

+0

물론, 알고리즘을 보여줄 필요는 없습니다. –

6

모든 목록의 첫 번째 요소로 구성된 "기본 목록"을 작성하십시오. 그런 다음 모든 목록의 모든 요소를 ​​반복합니다. 이러한 각 요소에 대해 해당 요소의 적절한 위치에 기본 목록을 업데이트하고이 업데이트 된 목록을 실행 목록의 목록에 추가하십시오.

아래 예제 구현을 포함 시켰습니다.

import java.util.ArrayList; 
import java.util.Arrays; 
import java.util.List; 

public class AdjacentListGenerator { 
    public static <T> List<List<T>> generateAdjacentLists(List<List<T>> lists) { 
     List<List<T>> result = new ArrayList<List<T>>(); 
     List<T> baseList = new ArrayList<T>(); 

     // Generate the base list, which is comprised of all the first elements 
     for (List<T> list : lists) { 
      baseList.add(list.get(0)); 
     } 
     result.add(baseList); 

     // Loop over each list, and for each element beyond the first, make a 
     // copy of the base list, update that element in place, and add it to 
     // our result 
     for (int list_i = 0; list_i < lists.size(); list_i++) { 
      List<T> list = lists.get(list_i); 
      for (int listElement_i = 1; listElement_i < list.size(); listElement_i++) { 
       List<T> updatedList = new ArrayList<T>(baseList); 
       updatedList.set(list_i, list.get(listElement_i)); 
       result.add(updatedList); 
      } 
     } 

     return result; 
    } 

    public static void main(String... args) { 
     List<String> a = Arrays.asList(new String[] { "a1", "a2", "a3" }); 
     List<String> b = Arrays.asList(new String[] { "b1", "b2" }); 
     List<String> c = Arrays.asList(new String[] { "c1", "c2", "c3" }); 
     List<List<String>> lists = new ArrayList<List<String>>(); 
     lists.add(a); 
     lists.add(b); 
     lists.add(c); 
     for (List<String> list : AdjacentListGenerator 
       .generateAdjacentLists(lists)) { 
      System.out.println(list); 
     } 
    } 
} 

출력

[a1, b1, c1] 
[a2, b1, c1] 
[a3, b1, c1] 
[a1, b2, c1] 
[a1, b1, c2] 
[a1, b1, c3] 
+0

+1 멋진 솔루션 –

1

내 대답은 이미 데이터 집합을 분류 한 것으로 가정하고 그들은 올바른 순서입니다.

public class SubsetPrinter 
{ 
    private static final String DELIMITER = ", "; 
    private static final String NEWLINE = System.getProperty("line.separator"); 

    public static String printSubsets(Map<String, List<String>> elements) 
    { 
    List<String> lines = new ArrayList<String>(); 
    for (Map.Entry<String, List<String>> entry : elements.entrySet()) 
    { 
     for (String sub : entry.getValue()) 
     { 
     String line = getLine(elements, entry.getKey(), sub); 
     if (!lines.contains(line)) 
     { 
      lines.add(line); 
     } 
     } 
    } 
    return asString(lines); 
    } 

    private static String getLine(Map<String, List<String>> elements, String element, String sub) 
    { 
    StringBuilder line = null; 
    for (Map.Entry<String, List<String>> entry : elements.entrySet()) 
    { 
     if (line == null) 
     { 
     line = new StringBuilder(); 
     } 
     else 
     { 
     line.append(DELIMITER); 
     } 
     if (entry.getKey().equals(element)) 
     { 
     line.append(sub); 
     } 
     else 
     { 
     line.append(entry.getValue().get(0)); // appends the first 
     } 
    } 
    return line.toString(); 
    } 

    private static String asString(List<String> lines) 
    { 
    StringBuilder sb = null; 
    for (String line : lines) 
    { 
     if (sb == null) 
     { 
     sb = new StringBuilder(); 
     } 
     else 
     { 
     sb.append(NEWLINE); 
     } 
     sb.append(line); 
    } 
    return sb.toString(); 
    } 
} 

그리고 테스트 존재 :

private Map<String, List<String>> getDataSet1() 
{ 
    Map<String, List<String>> map = new HashMap<String, List<String>>(); 
    List<String> subsetA = Arrays.asList(new String[] { "a1", "a2", "a3" }); 
    List<String> subsetB = Arrays.asList(new String[] { "b1", "b2" }); 
    List<String> subsetC = Arrays.asList(new String[] { "c1", "c2", "c3" }); 
    map.put("A", subsetA); 
    map.put("B", subsetB); 
    map.put("C", subsetC); 
    return map; 
} 

@Test 
public void testPrintSubsets() 
{ 
    Map<String, List<String>> elements = getDataSet1(); 
    String output = SubsetPrinter.printSubsets(elements); 
    System.out.println(output); 
} 

출력 :

a1, b1, c1 
a2, b1, c1 
a3, b1, c1 
a1, b2, c1 
a1, b1, c2 
a1, b1, c3 
2

모두가 내가 단지 배열을 해결하기 위해 노력할 것입니다 컨테이너를 사용하고 있습니다. 이것은 멀티 매핑 할 수 있습니다

:이 알고리즘에서

난 그냥 문제를 공식화

String[] lines = { "a1, a2, a3", "b1, b2", "c1, c2, c3" }; 

String[][] array = new String[lines.length][]; 
for (int i = 0; i < lines.length; i++) 
    array[i] = lines[i].replaceAll(" +", "").split(","); 

//lets type 1st row to ignore it in rest algoritm 
System.out.print(array[0][0]); 
for (int i = 1; i < array.length; i++) 
    System.out.print(", " + array[i][0]); 
System.out.println(); 

//in rest of algorithm we must surround each element by 
//1st element or rest rows, so lets iterate over each row 
for (int row = 0; row < array.length; row++) 
    //and surround its elements 
    for (int col = 1; col < array[row].length; col++) { 
     //left surround 
     int i=0; 
     for (; i<row; i++) 
      System.out.print(array[i][0]+", "); 
     // 
     System.out.print(array[row][col]); 
     //right surround 
     for (i=i+1; i<array.length; i++) 
      System.out.print(", "+array[i][0]); 
     System.out.println(); 
    } 
1

을 부분 집합 내가 나머지의 첫 번째 요소에 의해 집합의 다음 요소를 주변에 집중하고있어 다음 1 라인을 인쇄 무대 그래프.그냥 googled에 대한 diagrammatic illustration online of mult-stage graphs : 당신이하려고하는 것은 수퍼 - 소스 'S'에서 수퍼 싱크 'T'까지의 모든 경로를 인쇄하는 것입니다. 당신도 같은 것을 읽을 수 있습니다. 또한 관심이 있으시면 Network Flow problem과 관련이 있습니다.

관련 문제