如何为给定次数的试验创建所有可能的头或尾配置的数组?

问题描述 投票:0回答:1

我想用Java创建一个方法,返回一个字符串数组,其中包含所有可能的头或尾配置,并以试验次数作为参数

所以像simulate(3)这样的东西应该返回{“TTT”,“HTT”,“THT”,“TTH”,“HHT”,“HTH”,“THH”,“HHH”}。

我目前正在学习 AP CSA,还没有涉及继承和递归。有没有简单的方法可以实现这个方法?

java methods combinations coin-flipping
1个回答
0
投票

这是对我有用的解决方案

import java.util.List;

public class CoinToss {

// A method that takes the number of tosses and returns a list of all possible outcomes
public static List<String> sampleSpace(int n) {
// Base case: if n is zero, return an empty list
if (n == 0) {
return new ArrayList<>();
}
// Recursive case: get the sample space for n-1 tosses
List<String> previous = sampleSpace(n - 1);
// If the previous list is empty, add "H" and "T" as the first outcomes
if (previous.isEmpty()) {
previous.add("H");
previous.add("T");
} else {
// Otherwise, for each outcome in the previous list, append "H" and "T" and add them to a new list
List<String> current = new ArrayList<>();
for (String outcome : previous) {
current.add(outcome + "H");
current.add(outcome + "T");
}
// Return the new list as the sample space for n tosses
return current;
}
return previous;
}

// A method that prints the sample space for a given number of tosses
public static void printSampleSpace(int n) {
// Get the sample space as a list of strings
List<String> outcomes = sampleSpace(n);
// Print the size of the sample space
System.out.println("The sample space for " + n + " tosses has " + outcomes.size() + " outcomes.");
// Print each outcome in the sample space
for (String outcome : outcomes) {
System.out.println(outcome);
}
}

// A main method to test the program
public static void main(String[] args) {
// Print the sample space for 3 tosses
printSampleSpace(3);
}
}```
with following output 
[output of the above program having sample space when coin is tossed thrice][1]


  [1]: https://i.stack.imgur.com/xTtNQ.png
© www.soinside.com 2019 - 2024. All rights reserved.