如何在多行中随机排列两个字符?

huangapple go评论65阅读模式
英文:

How to randomize two characters in multiple Lines?

问题

import java.util.Random;

class GFG { 
    public static void main(String[] args) 
    { 
        test();
    }

    public static void test() {
        Random r = new Random();
        int i = r.nextInt(4) + 1;

        for (int k = 0; k < 10; k++) {
            int oCount = 10 - i;  // Calculate the count of "O" based on the random "X" count

            for (int m = 0; m < oCount; m++) {
                System.out.print("O");  // Print "O" without a new line
            }

            for (int j = 0; j < i; j++) {
                System.out.print("X");  // Print "X" without a new line
            }

            System.out.println();  // Move to the next line after printing one line of characters
        }
    }
}
英文:

I need a random number of 1-4 "X" while the remaining 6-9 characters are all going to be "O". This entire output needs to be printed into 10 lines within the console.

What I have so far is that I can generate 6 "O" and a random number from 1-4 of "X". However, I have no clue on how to make it happen that the X are randomly spread through the O and that the O will fill up the missing X.

In other words: If the code generates only 2 "X" I need to have 8 "O", in order to make 10 characters. Now I also have to print it into 10 lines.
I happen to be really new to java so the following code is all I have so far.

import java.util.Random;
  
class GFG { 
    public static void main(String[] args) 
    { 
        test();
    }

    public static void test() {
        Random r = new Random();
        int i = r.nextInt(4)+1;


        for (int k=5; k&lt;=5; k++) {
            for (int m=0; m&lt;=k; m++) {
                System.out.println(&quot;O&quot;);
            }
            for (int j=0; j&lt;=i; j++) {
                System.out.println(&quot;X&quot;);
            }
        }
    }
} 

答案1

得分: 2

这个方法生成一行类似于你想要的行:

public static String randomLine() {
    ArrayList<Character> characters = new ArrayList<>();

    Random random = new Random();
    int k = random.nextInt(4) + 1;
    for (int i = 1; i <= k; i++) {
        characters.add('X');
    }
    while (characters.size() < 10) {
        characters.add('O');
    }
    Collections.shuffle(characters); // 重新排列!!!
    String str = "";

    for (int i = 0; i < 10; i++) {
        str = str + characters.get(i);
    }
    return str;
}

如果需要的话,你可以将返回类型更改为 ArrayList<Character>
现在,要获取 10 行这样的内容,你可以运行以下代码:

for (int i = 0; i < 10; i++) {
    System.out.println(randomLine());
}
英文:

This method generates one line like the ones you desire :

public static String randomLine() {
	ArrayList&lt;Character&gt; characters= new ArrayList&lt;&gt;();

	Random random=new Random();
	int k=random.nextInt(4) + 1;
	for (int i = 1; i &lt;= k; i++) {
		characters.add(&#39;X&#39;);
		
	}
	while(characters.size()&lt;10) {
		characters.add(&#39;O&#39;);
	}
	Collections.shuffle(characters); //  Shuffling !!!
	String str=&quot;&quot;;
	
	for(int i=0;i&lt;10;i++)
		str=str+characters.get(i);
	return str;
	
}

You can change the return type to ArrayList&lt;Character&gt; if you want.
<br>Now, to get 10 of such lines you can run the following code:

for(int i=0;i&lt;10;i++)
    System.out.println(randomLine());

答案2

得分: 1

你可以在创建一个包含随机数量的X的数组/列表之后,使用现有的 Arrays.shuffle / Collections.shuffle 来随机排列你的数据数组/集合:

public static List<String> getRandomXOs() {
    Random random = new Random();
        
    int countX = 1 + random.nextInt(4);
    List<String> xos = IntStream.range(0, 10)
                                .mapToObj(i -> i < countX ? "X" : "O")
                                .collect(Collectors.toList());
    Collections.shuffle(xos);

    return xos;
}

// -------
// 测试
for (int i = 0; i < 5; i++) {
    System.out.println(getRandomXOs());
}

输出(随机):

[O, O, O, O, X, X, X, O, O, X]
[X, O, O, O, O, X, X, O, X, O]
[O, O, O, O, O, X, O, O, O, X]
[X, O, O, O, O, O, O, O, O, O]
[O, X, X, O, O, O, O, X, O, O]
英文:

You may use existing Arrays.shuffle / Collections.shuffle to randomize the array/collection of your data after creating an array/list containing random number of Xs:

public static List&lt;String&gt; getRandomXOs() {
    Random random = new Random();
        
    int countX = 1 + random.nextInt(4);
    List&lt;String&gt; xos = IntStream.range(0, 10)
                                .mapToObj(i -&gt; i &lt; countX ? &quot;X&quot; : &quot;O&quot;)
                                .collect(Collectors.toList());
    Collections.shuffle(xos);

    return xos;
}

// -------
// test
for (int i = 0; i &lt; 5; i++) {
    System.out.println(getRandomXOs());
}

Output (random):

[O, O, O, O, X, X, X, O, O, X]
[X, O, O, O, O, X, X, O, X, O]
[O, O, O, O, O, X, O, O, O, X]
[X, O, O, O, O, O, O, O, O, O]
[O, X, X, O, O, O, O, X, O, O]

答案3

得分: 1

使用Java8Stream库,您可以用更少的代码行更高效地解决问题。

这个test()函数有两个输入参数:x控制着要打印多少个 X,范围从 1xn控制着在单独的一行中要打印多少个 XO,就像您所请求的那样。

import java.util.Random;
import java.util.stream.*;

class CFG {
    public static void main(String[] args) {
        test(4, 10);
    }

    public static void test(int x, int n) {
        Random random = new Random();
        int countX = 1 + random.nextInt(x);

        String str = random
                .ints(1, n + 1)
                .distinct()
                .limit(n)
                .mapToObj(i -> i <= countX ? "X" : "O")
                .collect(Collectors.joining("\n"));

        System.out.println(str);
    }
}

随机输出:

X
O
O
X
O
O
O
O
X
O
英文:

Using the Java8 Stream library you can solve your problem more efficiently with less lines of code.

This test() function has inputs x which controls how many X are going to be printed ranging from 1 to x, and n which controls how many X or O will be printed in a separate line, as you requested.

import java.util.Random;
import java.util.stream.*;

class CFG {
    public static void main(String[] args) {
        test(4, 10);
    }

    public static void test(int x, int n) {
        Random random = new Random();
        int countX = 1 + random.nextInt(x);
        
        String str = random
                .ints(1, n + 1)
                .distinct()
                .limit(n)
                .mapToObj(i -&gt; i &lt;= countX ? &quot;X&quot; : &quot;O&quot;)
                .collect(Collectors.joining(&quot;\n&quot;));

        System.out.println(str);
    }
}

Random Output:

X
O
O
X
O
O
O
O
X
O

答案4

得分: 1

以下是与您的代码类似的可选代码部分:

import java.util.Random;

class main {
    public static void main(String[] args) {
        test();
    }

    public static void test() {
        Random r = new Random();
        int i = r.nextInt(4) + 1;

        int countX = 0;
        for (int j = 0; j < 10; j++) {
            int p = r.nextInt(2);
            if (p == 1) {
                System.out.println("O");
            } else {
                if (countX < i) {
                    System.out.println("X");
                    countX += 1;
                } else {
                    System.out.println("O");
                }
            }
        }
    }
}

随机输出结果:

X
X
X
O
X
O
O
O
O
O
英文:

Here is an optional code closer to yours

CODE:

import java.util.Random;
  
class main { 
    public static void main(String[] args) 
    { 
        test();
    }

    public static void test() {
        Random r = new Random();
        int i = r.nextInt(4)+1;

        int countX=0;
        for (int j=0; j&lt;10; j++){
            int p=r.nextInt(2);
            if (p==1) {
                System.out.println(&quot;O&quot;);
            }           
            else{
              if(countX&lt;i){
              System.out.println(&quot;X&quot;);
              countX+=1;
              }
              else{
                  System.out.println(&quot;O&quot;);
              }
            }
            
        }
    }
} 

RANDOM OUTPUT:

X
X
X
O
X
O
O
O
O
O

huangapple
  • 本文由 发表于 2020年9月16日 17:00:31
  • 转载请务必保留本文链接:https://go.coder-hub.com/63916624.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定