矩阵的组合(行和列)

时间:2018-02-17 22:17:54

标签: java eclipse matrix multidimensional-array

下午好,我在找到矩阵的所有组合时遇到了问题。

我正在使用4x4矩阵进行测试,但我无法获得其元素的大约2000种可能组合,但我只生成256种组合。我们的想法是考虑到达到这个数字的重复次数。

问题是我的算法没有创建行的组合。用2x2矩阵以图形方式解释:

Correct solution

正确的解决方案是上图,但它只生成4种组合。

Solution thrown by the algorithm

我的代码是:

package ia;

import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;

public class Nodo implements Iterator<String> {

Nodo anterior = null;
Nodo raiz = null;

int posicion = 0;   
List<String> columnas = new LinkedList<>(); 
int indicesTotales = 0;

public Nodo(List<String> columnas, Nodo anterior, Nodo raiz) {

    this.columnas = columnas;

    this.anterior = anterior;
    this.raiz = raiz;

    this.posicion = 0;
    this.indicesTotales = columnas.size() - 1;      
}

@Override
public boolean hasNext() {

    try {       
        if (this.raiz != null && this.raiz.posicion <= this.raiz.indicesTotales) {              
            return true;            
        } else if (this.posicion > this.indicesTotales) {               
            return false;           
        } else {            
            return false;           
        }       
    } catch (Exception exception) { 
        System.out.println(exception);      
    }
    throw new UnsupportedOperationException("Aún no es compatible.");   
}

@Override
public String next() {

    if (this.posicion >= this.indicesTotales) {

        if (this.anterior != null) {            
            this.posicion = 0;
            this.anterior.next();
        } else {
            ++this.posicion;            
        }       
    } else {        
        ++this.posicion;        
    }       
    return null;
}

public String actual() {
    return columnas.get(this.posicion); 
}

@Override
public void remove() {
    throw new UnsupportedOperationException("Not supported yet.");
}
}

2

package ia;

import java.util.Arrays;
import java.util.LinkedList;

public class Combinaciones {

private Nodo iterador = null;

public Combinaciones(String[][] lista) {

    Nodo raiz = null;
    Nodo aux = null;

    for (String[] columnas : lista) {

        aux = new Nodo(new LinkedList<>(Arrays.asList(columnas)), aux, raiz);

        if (raiz == null) {
            raiz = aux;
        }
    }
    iterador = aux;
}

public int generar() {

    int contador = 0;

    while (iterador.hasNext()) {
        Nodo aux = iterador;
        System.out.print(aux.actual());
        while (aux.anterior != null) {
            System.out.print(" " + aux.anterior.actual());
            aux = aux.anterior;
        }
        iterador.next();
        System.out.println();
        contador++;
    }
    return contador;
}
}

3

package ia;

public class Prueba {

public static void main(String[] args) {
    Combinaciones lista = new Combinaciones(
            new String[][] { { "1", "2" }, { "3", "4" } } );
    System.out.println("\n" + lista.generar());
}
}

如果有人能帮我解决错误,我将不胜感激。 Tranks。

0 个答案:

没有答案