草庐IT

java - JAVA 字符数组中的特定元素排列?

coder 2024-03-18 原文

如何列出字符数组中指定的任何字母的所有大写/小写排列? 所以,假设我有一个这样的字符数组:['h','e','l','l','o'] 我想打印出字母“l”的可能组合,以便打印出 [hello,heLlo,heLLo,helLo]。

这是我到目前为止所拥有的(唯一的问题是我可以打印排列,但是我无法在实际单词中打印它们。所以我的代码打印 [ll,lL,Ll,LL] 而不是上面的例子。

我的代码:

import java.util.ArrayList;
import java.util.HashSet;

public class Main {

public static void main(String[] args) {
    //Sample Word
    String word = "Tomorrow-Today";

    //Sample Letters for permutation
    String rule_char_set = "tw";


    ArrayList<Character> test1 = lettersFound(word, rule_char_set);

    printPermutations(test1);







}

public static void printPermutations(ArrayList<Character> arrayList) {
    char[] chars = new char[arrayList.size()];
    int charIterator = 0;

    for(int i=0; i<arrayList.size(); i++){
        chars[i] = arrayList.get(i);
    }

    for (int i = 0, n = (int) Math.pow(2, chars.length); i < n; i++) {
        char[] permutation = new char[chars.length];
        for (int j =0; j < chars.length; j++) {
            permutation[j] = (isBitSet(i, j)) ? Character.toUpperCase(chars[j]) : chars[j];
        }
        System.out.println(permutation);
    }
}

public static boolean isBitSet(int n, int offset) {
    return (n >> offset & 1) != 0;
}

public static ArrayList<Character> lettersFound(String word, String rule_char_set) {

    //Convert the two parameter strings to two character arrays
    char[] wordArray = word.toLowerCase().toCharArray();
    char[] rule_char_setArray = rule_char_set.toLowerCase().toCharArray();

    //ArrayList to hold found characters;
    ArrayList<Character> found = new ArrayList<Character>();

    //Increments the found ArrayList that stores the existent values.
    int foundCounter = 0;


    for (int i = 0; i < rule_char_setArray.length; i++) {
        for (int k = 0; k < wordArray.length; k++) {
            if (rule_char_setArray[i] == wordArray[k]) {
                found.add(foundCounter, rule_char_setArray[i]);
                foundCounter++;

            }
        }
    }
    //Convert to a HashSet to get rid of duplicates
    HashSet<Character> uniqueSet = new HashSet<>(found);

    //Convert back to an ArrayList(to be returned) after filtration of duplicates.
    ArrayList<Character> filtered = new ArrayList<>(uniqueSet);

    return filtered;
}

}

最佳答案

您需要对程序进行少量更改。您的逻辑是完美的,您需要首先找到要在给定单词中更改的 characters 。找到它们后,找到 characterspowerset 来打印所有排列,但这只会打印 rule-char 字符的 permuatation -set 出现在给定单词中。

您需要做的改动很少,首先找到word 的所有indexes,其中包含rule-char-set 的字符。然后找到存储在 ArrayList 中的索引的所有 subsets,然后对于每个子集中的每个元素,使 character 出现在 上>index 到大写字母,这将为您提供所需的所有排列

考虑一个 word = "Hello"rule-char-set="hl" 的例子 那么首先你需要找到 h 的所有索引l 在字符串 word 中。

所以这里的索引是0,2,3。将它存储在 ArrayList 中,然后找到它的 powerset。然后对于每个 subset ,让 character 出现在那个 indexuppercase 字母。

Word[] = {'h','e','l','l','o'}
indexes =  0 , 1 , 2 , 3 , 4


index[]= { 0 , 2 ,3}  //Store the indexes of characters which are to be changed


BITSET      |       SUBSET      |       word

000         |         -         |       hello 
001         |        {3}        |       helLo 
010         |        {2}        |       heLlo 
011         |       {2,3}       |       heLLo 
100         |        {0}        |       Hello 
101         |       {0,3}       |       HelLo 
110         |       {0,2}       |       HeLlo 
111         |      {0,2,3}      |       HeLLo 

代码:

import java.util.ArrayList;
import java.util.HashSet;

public class Main {

    public static void main(String[] args) {
        //Sample Word
        String word = "Tomorrow-Today";

        //Sample Letters for permutation
        String rule_char_set = "tw";


        ArrayList<Integer> test1 = lettersFound(word, rule_char_set); //To store the indexes of the characters

        printPermutations(word,test1);

    }

    public static void printPermutations(String word,ArrayList<Integer> arrayList) {
        char word_array[]=word.toLowerCase().toCharArray();
        int length=word_array.length;
        int index[]=new int[arrayList.size()];

        for(int i=0; i<arrayList.size(); i++){
            index[i] = arrayList.get(i);
        }

        for (int i = 0, n = (int) Math.pow(2, index.length); i < n; i++) {
            char[] permutation = new char[length];

            System.arraycopy(word_array,0,permutation,0,length);    

            //First copy the original array and change 
            //only those character whose indexes are present in subset

            for (int j =0; j < index.length; j++) {
                permutation[index[j]] = (isBitSet(i, j)) ? Character.toUpperCase(permutation[index[j]]) : permutation[index[j]];
            }
            System.out.println(permutation);
        }
    }

    public static boolean isBitSet(int n, int offset) {
        return (n >> offset & 1) != 0;
    }

    public static ArrayList<Integer> lettersFound(String word, String rule_char_set) {

        //Convert the two parameter strings to two character arrays
        char[] wordArray = word.toLowerCase().toCharArray();
        char[] rule_char_setArray = rule_char_set.toLowerCase().toCharArray();

        //ArrayList to hold found characters;
        ArrayList<Integer> found = new ArrayList<Integer>();

        //Increments the found ArrayList that stores the existent values.
        int foundCounter = 0;


        for (int i = 0; i < rule_char_setArray.length; i++) {
            for (int k = 0; k < wordArray.length; k++) {
                if (rule_char_setArray[i] == wordArray[k]) {
                    found.add(foundCounter, k);       //Store the index of the character that matches
                    foundCounter++;

                }
            }
        }
        return found;
    }

}

输出:

tomorrow-today
Tomorrow-today
tomorrow-Today
Tomorrow-Today
tomorroW-today
TomorroW-today
tomorroW-Today
TomorroW-Today

关于java - JAVA 字符数组中的特定元素排列?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43773952/

有关java - JAVA 字符数组中的特定元素排列?的更多相关文章

  1. ruby - 如何从 ruby​​ 中的字符串运行任意对象方法? - 2

    总的来说,我对ruby​​还比较陌生,我正在为我正在创建的对象编写一些rspec测试用例。许多测试用例都非常基础,我只是想确保正确填充和返回值。我想知道是否有办法使用循环结构来执行此操作。不必为我要测试的每个方法都设置一个assertEquals。例如:describeitem,"TestingtheItem"doit"willhaveanullvaluetostart"doitem=Item.new#HereIcoulddotheitem.name.shouldbe_nil#thenIcoulddoitem.category.shouldbe_nilendend但我想要一些方法来使用

  2. Ruby 解析字符串 - 2

    我有一个字符串input="maybe(thisis|thatwas)some((nice|ugly)(day|night)|(strange(weather|time)))"Ruby中解析该字符串的最佳方法是什么?我的意思是脚本应该能够像这样构建句子:maybethisissomeuglynightmaybethatwassomenicenightmaybethiswassomestrangetime等等,你明白了......我应该一个字符一个字符地读取字符串并构建一个带有堆栈的状态机来存储括号值以供以后计算,还是有更好的方法?也许为此目的准备了一个开箱即用的库?

  3. ruby - 其他文件中的 Rake 任务 - 2

    我试图在一个项目中使用rake,如果我把所有东西都放到Rakefile中,它会很大并且很难读取/找到东西,所以我试着将每个命名空间放在lib/rake中它自己的文件中,我添加了这个到我的rake文件的顶部:Dir['#{File.dirname(__FILE__)}/lib/rake/*.rake'].map{|f|requiref}它加载文件没问题,但没有任务。我现在只有一个.rake文件作为测试,名为“servers.rake”,它看起来像这样:namespace:serverdotask:testdoputs"test"endend所以当我运行rakeserver:testid时

  4. ruby-on-rails - 在 Rails 中将文件大小字符串转换为等效千字节 - 2

    我的目标是转换表单输入,例如“100兆字节”或“1GB”,并将其转换为我可以存储在数据库中的文件大小(以千字节为单位)。目前,我有这个:defquota_convert@regex=/([0-9]+)(.*)s/@sizes=%w{kilobytemegabytegigabyte}m=self.quota.match(@regex)if@sizes.include?m[2]eval("self.quota=#{m[1]}.#{m[2]}")endend这有效,但前提是输入是倍数(“gigabytes”,而不是“gigabyte”)并且由于使用了eval看起来疯狂不安全。所以,功能正常,

  5. ruby-on-rails - Ruby net/ldap 模块中的内存泄漏 - 2

    作为我的Rails应用程序的一部分,我编写了一个小导入程序,它从我们的LDAP系统中吸取数据并将其塞入一个用户表中。不幸的是,与LDAP相关的代码在遍历我们的32K用户时泄漏了大量内存,我一直无法弄清楚如何解决这个问题。这个问题似乎在某种程度上与LDAP库有关,因为当我删除对LDAP内容的调用时,内存使用情况会很好地稳定下来。此外,不断增加的对象是Net::BER::BerIdentifiedString和Net::BER::BerIdentifiedArray,它们都是LDAP库的一部分。当我运行导入时,内存使用量最终达到超过1GB的峰值。如果问题存在,我需要找到一些方法来更正我的代

  6. ruby-on-rails - unicode 字符串的长度 - 2

    在我的Rails(2.3,Ruby1.8.7)应用程序中,我需要将字符串截断到一定长度。该字符串是unicode,在控制台中运行测试时,例如'א'.length,我意识到返回了双倍长度。我想要一个与编码无关的长度,以便对unicode字符串或latin1编码字符串进行相同的截断。我已经了解了Ruby的大部分unicode资料,但仍然有些一头雾水。应该如何解决这个问题? 最佳答案 Rails有一个返回多字节字符的mb_chars方法。试试unicode_string.mb_chars.slice(0,50)

  7. ruby-on-rails - Rails 3 中的多个路由文件 - 2

    Rails2.3可以选择随时使用RouteSet#add_configuration_file添加更多路由。是否可以在Rails3项目中做同样的事情? 最佳答案 在config/application.rb中:config.paths.config.routes在Rails3.2(也可能是Rails3.1)中,使用:config.paths["config/routes"] 关于ruby-on-rails-Rails3中的多个路由文件,我们在StackOverflow上找到一个类似的问题

  8. ruby - 将差异补丁应用于字符串/文件 - 2

    对于具有离线功能的智能手机应用程序,我正在为Xml文件创建单向文本同步。我希望我的服务器将增量/差异(例如GNU差异补丁)发送到目标设备。这是计划:Time=0Server:hasversion_1ofXmlfile(~800kiB)Client:hasversion_1ofXmlfile(~800kiB)Time=1Server:hasversion_1andversion_2ofXmlfile(each~800kiB)computesdeltaoftheseversions(=patch)(~10kiB)sendspatchtoClient(~10kiBtransferred)Cl

  9. ruby-on-rails - 在 Ruby 中循环遍历多个数组 - 2

    我有多个ActiveRecord子类Item的实例数组,我需要根据最早的事件循环打印。在这种情况下,我需要打印付款和维护日期,如下所示:ItemAmaintenancerequiredin5daysItemBpaymentrequiredin6daysItemApaymentrequiredin7daysItemBmaintenancerequiredin8days我目前有两个查询,用于查找maintenance和payment项目(非排他性查询),并输出如下内容:paymentrequiredin...maintenancerequiredin...有什么方法可以改善上述(丑陋的)代

  10. ruby-on-rails - Rails 常用字符串(用于通知和错误信息等) - 2

    大约一年前,我决定确保每个包含非唯一文本的Flash通知都将从模块中的方法中获取文本。我这样做的最初原因是为了避免一遍又一遍地输入相同的字符串。如果我想更改措辞,我可以在一个地方轻松完成,而且一遍又一遍地重复同一件事而出现拼写错误的可能性也会降低。我最终得到的是这样的:moduleMessagesdefformat_error_messages(errors)errors.map{|attribute,message|"Error:#{attribute.to_s.titleize}#{message}."}enddeferror_message_could_not_find(obje

随机推荐