为什么我的方法不是按照我想要的方式在矩阵中对列进行排序?

时间:2015-04-10 18:06:16

标签: java sorting matrix multidimensional-array keyword

我想取一个用户输入的关键字,然后按字母顺序对其进行排序,然后将其下面的cols放在关键字的字符排序后的位置,例如:

在:

   K E Y S
   V V V X 
   D V G G 
   D F D V 

后:

   E K S Y
   V V X V
   V D G G
   F D V D

我的输出:

 E K S Y
 V V V X 
 D V G G 
 D F D V 

我的方法不会按照我想要的方式对信息进行排序:

public String sortMatrix(String a [][]){



        System.out.println("\nAlphabetically rearranged: ");
        char[] key = polyCipher.getKeyword().toCharArray();
        char[] alphaKey = polyCipher.getKeyword().toCharArray();
        String alphaOut = "";

        //sort the key
        Arrays.sort(alphaKey);
        // set up temp array x

       //String a [][] = {{"V", "V", "V", "X"},{"D", "V", "G", "G"},{"D", "F", "D", "V"}};

        char[][] x = new char[a.length+1][];
        x[0] = alphaKey;

        for(int loop1 = 0; loop1 < a.length; loop1++){
            x[loop1+1] = new char[a[loop1].length];
            for (int loop2 = 0; loop2 < a[loop1].length; loop2++){
                x[loop1+1][loop2] = a[loop1][loop2].charAt(0);
            }
        }

        for(int loop1 = 0; loop1 < a.length; loop1++){
            x[loop1+1] = new char[a[loop1].length];
            for (int loop2 = 0; loop2 < a[loop1].length; loop2++){
                x[loop1+1][loop2] = a[loop1][loop2].charAt(0);
            }
        }


            /* x[0] = new char[]{'J', 'A', 'V', 'A'};
               x[1] = new char[]{'A', 'B', 'C', 'D'};
               x[2] = new char[]{'A', 'B', 'C', 'D'};
               x[3] = new char[]{'A', 'B', 'C', 'D'}; */


            String [] strArray = new String[x[0].length];

            for (int loop1 = 0; loop1 < x.length; loop1++){
                for (int loop2 = 0; loop2 < x[0].length; loop2++){
                    if(strArray[loop2] == null){
                        strArray[loop2] = "";
                    }
                    strArray[loop2] += x[loop1][loop2];
                }
            }

            Arrays.sort(strArray);


            for (int loop1 = 0; loop1 < strArray.length; loop1++){
                for (int loop2 = 0; loop2 < strArray[loop1].length(); loop2++){
                    x[loop2][loop1] = strArray[loop1].charAt(loop2);
                }
            }

            Arrays.sort(key);
            alphaOut += "\n";
            for (int i = 0; i < x.length; i++) {
           //     keyOut += PHRASE_KEY[i] + " ";
               for (int j = 0; j < x[i].length; j++) {
                   alphaOut += x[i][j] + " ";
                }
               alphaOut += "\n";
            }

           return alphaOut.toUpperCase();


    }

3 个答案:

答案 0 :(得分:1)

我稍微更改了代码。我希望它可以帮助你。我知道应该更改代码以使其工作,但这是一个有效的例子:)

import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

/**
 *
 * @author Pasban
 */
public class sortmatrix {

    public static void main(String[] args) {
        String[] list = {"KVDD", "EVVF", "YVGD", "SXGV"};
        List<String> data = Arrays.asList(list);
        Collections.sort(data, new CustomComparator());
        int maxLen = 0;
        for (String str : data) {
            maxLen = Math.max(maxLen, str.length());
        }
        for (int i = 0; i < maxLen; i++) {
            for (String str : data) {
                if (str.length() > i) {
                    System.out.print(str.charAt(i));
                } else {
                    System.out.print(" ");
                }
            }
            System.out.println();
        }
    }

    public static class CustomComparator implements Comparator<String> {

        @Override
        public int compare(String o1, String o2) {
            return (o1.charAt(0) + "").compareTo(o2.charAt(0) + "");
        }
    }
}

输出:

**

EKSY
VVXV
VDGG
FDVD

**

如果列的大小是固定的,则:

public static void main(String[] args) {
        String[] list = {"KVDD", "EVVF", "YVGD", "SXGV"};
        List<String> data = Arrays.asList(list);
        Collections.sort(data, new CustomComparator());
        int maxLen = 4;
        for (int i = 0; i < maxLen; i++) {
            for (String str : data) {
                System.out.print(str.charAt(i));
            }
            System.out.println();
        }
    }

答案 1 :(得分:1)

我添加了二维排序。我用冒泡排序。输出完全相同。 2D排序要好得多,因为您可以在关键部分拥有更多的一个字符。字符串排序只是查看第一个char,它可能看起来像一个限制。

import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

/**
 *
 * @author Pasban
 */
public class sortmatrix {

    public static String[] sortString(String[] inp) {
        List<String> data = Arrays.asList(inp);
        Collections.sort(data, new CustomComparator());
        return data.toArray(new String[0]);
    }

    public static String[][] sortString2D(String[][] inp) {

        String[][] out = inp;

        //inp.length number columns
        for (int i = 0; i < inp.length; i++) { // bubble sort
            for (int j = i + 1; j < inp.length; j++) {
                if (out[i][0].compareTo(out[j][0]) > 0) { // string comparison :)
                    String[] tmp;
                    tmp = out[i];
                    out[i] = out[j];
                    out[j] = tmp;
                }
            }
        }

        return out;
    }

    public static void main(String[] args) {


        String[][] list2D = new String[][]{
            {"K", "V", "D", "D"},
            {"E", "V", "V", "F"},
            {"Y", "V", "G", "D"},
            {"S", "X", "G", "V"}
        };

        String[][] data2D = sortString2D(list2D);

        for (int j = 0; j < data2D[0].length; j++) {
            for (int i = 0; i < data2D.length; i++) {
                System.out.print(data2D[i][j]);
            }
            System.out.println();
        }

        System.out.println(" ----- ");


        String[] list = {"KVDD", "EVVF", "YVGD", "SXGV"};
        String[] data = sortString(list);

        int maxLen = data[0].length();
        for (int i = 0; i < maxLen; i++) {
            for (String str : data) {
                System.out.print(str.charAt(i));
            }
            System.out.println();
        }
    }

    public static class CustomComparator implements Comparator<String> {

        @Override
        public int compare(String o1, String o2) {
            return (o1.charAt(0) + "").compareTo(o2.charAt(0) + "");
        }
    }
}

答案 2 :(得分:0)

以下是我所做的更改:

在Matrix类中,填充矩阵[] [],

自:

matrix[i][j] = validChars.split("")[random].charAt(0);

matrix[i][j] =  validChars.charAt(random);

请注意,当您使用拆分(&#34;&#34;)时,第一项始终为空字符串。空字符串没有任何字符,因此获取第一个字符毫无意义。这给我带来了一些错误,但我终于找到了。嘿,你可以直接从字符串中获取charAt()的char,然后你为什么要拆分它? :)

接下来,在sortMatrix()中,使用Arrays.sort(alphaKey)对键进行排序;没有排序,或者让我们先将它们连接到您的列。因此,您的密钥和内容之间的连接将被破坏。 bellow是将内容与键行排序的正确方法。

我还添加了rotateMatrix()方法。如果要替换列,则必须逐个交换每一行中的每一列。因此,我旋转矩阵,只是交换旋转矩阵的行。 Java逐行保留矩阵,但我们希望逐列(我希望你明白这一点:))

public String[][] rotateMatrix(String inp[][]) {
    int L1 = inp.length;
    int L2 = inp[0].length;
    String[][] ret = new String[L2][L1];
    for (int i = 0; i < L1; i++) {
        for (int j = 0; j < L2; j++) {
            ret[j][i] = inp[i][j];
        }
    }
    return ret;
}

作业完成后,我旋转矩阵以反转旋转。

这是最终的排序矩阵:

public String[][] sortMatrix(String a[][]) {

    System.out.println("\nAlphabetically rearranged: ");
    char[] key = polyCipher.getKeyword().toCharArray();

    //sort the key
    //Arrays.sort(alphaKey); // 

    //copy the array
    String[][] out = rotateMatrix(a);

    //inp.length number columns
    for (int i = 0; i < key.length; i++) { // bubble sort
        for (int j = i + 1; j < key.length; j++) {
            if (key[i] > key[j]) { // string comparison :)
                //sort the header
                char c = key[i];
                key[i] = key[j];
                key[j] = c;
                //sort the column
                String[] tmp;
                tmp = out[i];
                out[i] = out[j];
                out[j] = tmp;
            }
        }
    }

    System.out.print("Sorted Key: ");
    for (int i = 0; i < key.length; i++) {
        System.out.print(key[i]);
    }
    System.out.println();

    /*
    for (int i = 0; i < out.length; i++) {
    for (int j = 0; j < out[0].length; j++) {
    System.out.print(out[i][j]);
    }
    System.out.println();
    }*/

    return rotateMatrix(out);
}

其余代码保持不变。您不再需要customComprator,请将其删除。

在我之前的答案中,如果您已使用键(inp [0] [] = keys []将输入矩阵的第一行填充到排序矩阵中,inp [1..length + 1] [] = a [0..length] []),它对你有用,关于那里提供的示例矩阵:D