【问题标题】:Randomize and shuffling a string without using stringbuilder or power tools在不使用 stringbuilder 或电动工具的情况下随机化和改组字符串
【发布时间】:2020-10-01 16:43:15
【问题描述】:

我想在不使用任何数组、StringBuilder 或电动工具(为您工作的包或方法)和使用Math.random() 的情况下对字符串进行洗牌。

我下面的代码有效,但我不喜欢它,因为我不能使用字符串生成器或.append()。有人可以帮我解决吗?

public class loopPrr
{
  static String shuffle(int a) {
       
    String s = "BaaBooDaaDoo";
    StringBuilder sb = new StringBuilder(a); 
  
    for (int i = 0; i < a; i++) { 
      int r = (int)(s.length() * Math.random()); 
  
      sb.append(s.charAt(r)); 
    } 
  
    return sb.toString();         
  }
}

【问题讨论】:

  • 您需要打乱现有字符串还是生成一个长度为a 的新随机字符串,其中包含来自硬编码模式的字符?

标签: java string for-loop shuffle


【解决方案1】:

如果我没看错,你可以简单地使用字符串:

static String shuffle(int a) {
    String s = "BaaBooDaaDoo";

    String sb = "";

    for (int i = 0; i < a; i++) {
        int r = (int) (s.length() * Math.random());

        sb += s.charAt(r);
    }

    return sb;
}

我建议更改“sb”变量的名称以避免误解。

【讨论】:

    【解决方案2】:

    可以通过将Fisher--Yates algorithm 应用于输入字符串的字符数组来打乱字符串。

    该算法主要在于交换随机索引处的字符,如下所示。

    static String shuffle(String str) {
        char[] arr = str.toCharArray();
        for (int i = str.length() - 1; i > 0 ; i--) { // starting from the last character
            int x = (int)(i * Math.random()); // next index is in range [0...i-1]
            char t = arr[i];
            arr[i] = arr[x];
            arr[x] = t;
        }
        return new String(arr);
    }
    

    如果需要从预定义的字母表中生成一个长度为a的随机字符串,可以在之前对String的实现的基础上实现以下方法,以保证在a &gt;= alphabet.length时至少使用一次字母表的所有字符:

    private static final String LETTERS = "AaBbCcDdEe";
    
    static String shuffle(int a) {
        if (a <= 0) {
            return "";
        }
        if (a < LETTERS.length()) {
            char[] res = new char[a];
            for (int i = 0, x = LETTERS.length(); x > 0 && i < a; i++, x--) {
                res[i] = LETTERS.charAt((int)(Math.random() * x));
            }
            return new String(res);
        }
        return shuffle(shuffle(LETTERS) + shuffle(a - LETTERS.length()));
    }
    

    【讨论】:

      猜你喜欢
      • 2020-12-30
      • 2022-09-27
      • 2021-12-03
      • 2011-03-20
      • 2019-10-12
      • 2023-03-09
      • 1970-01-01
      • 2021-10-02
      • 1970-01-01
      相关资源
      最近更新 更多