java 方法/函数,用于为类似于Excel的电子表格应用程序生成列名

hsgswve4  于 2023-03-21  发布在  Java
关注(0)|答案(5)|浏览(147)

我试图实现下面的输出,例如,如果我传递5到函数columnNames,它应该打印A,B,C,D,E,如果传递27,它应该打印A,B,C,D,E...AA,AB,AC等。
我需要处理下面的代码片段,我只需要处理columnNames方法。

import java.io.*;
import java.util.*;
import java.text.*;
import java.math.*;
import java.util.regex.*;

public class Tester {
    static List<String> columnNames(int n) {
        List<String> result = new ArrayList<String>();
        return result;
    }

    public static void main(String[] args) throws IOException {
        Scanner in = new Scanner(System.in);

        int _columns = Integer.parseInt(in.nextLine().trim());

        List<String> result = columnNames(_columns);

        System.out.println(String.join(", ", result));
    }
}

当我将这个代码段添加到columnNames方法并将5传递给参数时,它只打印与我输入的数字相等的列字母。2然而,我期望看到A,B,C,D,E。

StringBuilder sb = new StringBuilder();
while (n > 0) {
    for (int i = 0; i < n; i++) {
        n--;
        char ch = (char) (n % 26 + 'A');
        n /= 26;
        sb.append(ch);
        result.add(sb.toString());
    }
}
sb.reverse();

谢谢你的帮助。

piah890a

piah890a1#

我设法用下面的代码弄明白了。感谢那些在某种程度上帮助过我的人。

static List<String> columnNames(int n) {
    List<String> result = new ArrayList<String>();

    String alphabets[] = {"A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z"};
    StringBuilder sb = new StringBuilder();
    for(int j = 0; j < n; j++){
        int index = j/26;   
            char ch = (char) (j % 26 + 'A');               
          sb.append(ch);
          String item = "";
          if(index > 0) {
              item += alphabets[index-1];
          }
          item += alphabets[j % 26];
          result.add(item);
    }
    sb.reverse();
    return result;
}
m0rkklqb

m0rkklqb2#

这正是你想要的。

static List<String> columnNames(int n) 
{
    List<String> result = new ArrayList<String>();

    String[] alphs = new String[] {"A","B","C","D","E","F","G","H","I","J","K","L","M","N",
            "O","P","Q","R","S","T","U","V","W","X","Y","Z"};


    if(n>-1 && n<27)
    {
        for(int i=0; i<n;i++)
        {
            result.add(alphs[i]);
        }

    }
    else
    {

        for(int i=0;i<26;i++)
        {
            result.add(alphs[i]);   
            n--;
        }

        for(int i=0;i<result.size();i++)
        {
            for(int j=0; j<26; j++)
            {
                if(n!=0)
                {
                    result.add(result.get(i).concat(alphs[j]));
                    n--;
                }
                else
                {
                    return result;
                }

            }

        }

    }

    return result;
}
46scxncf

46scxncf3#

对于n〉702,代码无法退出并运行
Java Doodle link Work upto 'ZZ' sequence

whitzsjs

whitzsjs4#

这段代码生成了你想要的:

StringBuilder sb;

char current = 'A';

for (int i = 0; i < n; i++) {
    // new StringBuilder for every String
    sb = new StringBuilder();

    // If 'i' exceeds letters, use the ones you have already added to your List
    if (i > 25)
        sb.append(result.get(i - 26));

    // Append current character
    sb.append(current);

    // Add it to your List
    result.add(sb.toString());

    // Get the next letter while making sure it will not surpass 'Z'
    if (current == 'Z')
        current = 'A';
    else
        current = (char) (current + 1);
}
nwlls2ji

nwlls2ji5#

给你。

private static final List<String> englishCapitalAlphabet = Arrays.asList("A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z");

private static int findClosestPowerOfXApprochingNFromTheHigherEnd(int x, int n) {
    int power = 1;
    while (Math.pow(x, power) < n) {
        power += 1;
    }
    return power;
}

private static String generatePermutativeLabel(List<String> primitives, int serialNumber) {
    int places = findClosestPowerOfXApprochingNFromTheHigherEnd(primitives.size(), serialNumber);
    String label = "";
    for (int i = (places - 1); i >= 0; i--) {
        label += primitives.get((int) Math.floor((serialNumber / Math.pow(primitives.size(), i)) - 1));
        serialNumber %= Math.pow(primitives.size(), i);
    }
    return label;
}

public static String generatePermutativeLabelWithCapitalAlphabets(int serialNumber) {
    return generatePermutativeLabel(englishCapitalAlphabet, serialNumber);
}

不幸的是,上面的代码没有考虑到这些标签没有零的表示的事实,这在下面的代码中已经被纠正,并且它将适用于任意长的标签。

/* Assumes the labels represent a Natural Number Sequence.
 * The Set of Characters involed in the labelling are assumed to have an order and they are pre-defined,
 * and they are incrementally numbered in that order start from the number one.
 * The right most character's (RMC) value is multiplied by,
 * the total count of the valid characters (TC) raised to the power zero,
 * the value of next character to the RMC is multiplied by TC raised to the power one and so on.
 * Example: for the set (A, B, C):
 *     TC is 3
 *     the label "A" has the value 1
 *     the label "C" has the value 3
 *     the label "ACBA" has the value 1321 (1 * 3^3 + 3 * 3^2 + 2 * 3^1 + 1 * 3^0)
 */

private static final List<String> englishCapitalAlphabet = Arrays.asList("A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z");

private static int findClosestPowerOfXApprochingNFromTheHigherEnd(int x, int n) {
    int power = 1;
    while (Math.pow(x, power) < n) {
        power += 1;
    }
    return power;
}

/* Returns the number sequence without multiplying it with the positional coefficient
 */
private static List<Integer> generatePermutativeSequence(int totalCount, int number) {
    int places = findClosestPowerOfXApprochingNFromTheHigherEnd(totalCount, number);
    List<Integer> bareValues = new ArrayList<>(Collections.nCopies(places, 0));
    for (int i = (places - 1); i >= 0; i--) {
        bareValues.set(i, (int) Math.floor(number / Math.pow(totalCount, i)));

        number %= Math.pow(totalCount, i);
        if (number == 0) {
            break;
        }
    }
    return bareValues;
}

/* Assumes that the Left Most Value will not needed to be borrowed from.
 * Assumes that all zero sequences will be optionally preceded (in the left most side) by a sequence of mixed zeros and ones,
 * and immediately preceded by a number greater than one.
 * Assumes Whole Numbers only.
 */
private static List<Integer> rearrangeToEliminateZeros(int totalCount, List<Integer> bareValues) {
    if (!bareValues.contains(0)) {
        return bareValues;
    }

    // finding the sequence to be rearranged
    int lastZeroIndex = bareValues.lastIndexOf(0);
    int lastNonZeroOrOneIndex = lastZeroIndex;
    while (bareValues.get(lastNonZeroOrOneIndex).equals(0) || bareValues.get(lastNonZeroOrOneIndex).equals(1)) {
        lastNonZeroOrOneIndex += 1;
    }

    // rearranging
    for (int i = lastNonZeroOrOneIndex; i > lastZeroIndex; i--) {
        bareValues.set(i, bareValues.get(i) - 1);
        bareValues.set(i - 1, bareValues.get(i - 1) + totalCount);
    }

    return rearrangeToEliminateZeros(totalCount, bareValues);
}

public static String generatePermutativeLabel(List<String> primitives, int serialNumber) {
    if (serialNumber < 1) {
        throw new IllegalArgumentException("Only Natural Numbers can be labeled.");
    }

    int totalCount = primitives.size();
    if (totalCount < 2) {
        throw new IllegalArgumentException("Total count cannot be lesser than two.");
    }

    List<Integer> bareValues = rearrangeToEliminateZeros(totalCount, generatePermutativeSequence(totalCount, serialNumber));
    Collections.reverse(bareValues);
    String label = "";
    for (Integer i : bareValues) {
        label += primitives.get(i - 1);
    }
    return label;
}

public static String generatePermutativeLabelWithCapitalAlphabets(int serialNumber) {
    return generatePermutativeLabel(englishCapitalAlphabet, serialNumber);
}

相关问题