gpt4 book ai didi

java - 在数组中查找连续的重复整数

转载 作者:行者123 更新时间:2023-11-30 06:10:30 24 4
gpt4 key购买 nike

我遇到一个问题,我需要询问用户输入他们希望掷骰子的次数,然后创建并打印一个包含所请求掷骰数的数组。到目前为止,我可以创建数组,但是问题的另一部分是每当有连续的​​重复滚动时,我必须在它们周围加上括号。例如输入 11,创建数组

{1 , 2 , 1 , 4 , 4, 6 , 2 , 3 , 5 , 5 , 5} 会输出 1 2 1 ( 4 4 ) 6 2 3 ( 5 5 5 )

到此为止

import java.util.Scanner;
import java.util.Random;

public class HW0603 {

public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("How many times would you like to roll: ");
System.out.println();
int x = input.nextInt();
run(rolls(x), x);
}

public static int[] rolls(int x) {
Random random = new Random();
int y[] = new int[x];
for (int i = 0; i < x; i++) {
int z = random.nextInt(6) + 1;
y[i] = z;
}
return y;
}

public static void run(int a[], int b) {
for (int i = 1; i < b; i++) {
System.out.print(a[i] + " ");
}
}
}

至于括号,老实说我不知道​​如何开始。使用 if 语句对我不起作用,因为我将 a[i]a[i+1] 进行比较,所以我的 if 语句变体似乎会出现越界错误和 a[i-1]。谁能给我一个开始的地方或一些提取连续重复项的提示?

最佳答案

你需要比较当前项目和下一个项目如果相等,打印“(”然后打印项目制作旗帜 paranOpened您已经打开 (,所以您不会再次重新打开 (,以避免这种情况:1 (2(2(2...,然后当 curr!=next 时,根据该标志打印项目或打印项目然后关闭“)”

循环结束

打印被排除在循环之外的纬度项目 (b-1) ..;i < b - 1;.. , 检查是否打开了 "("

你的run()方法是这样的

static boolean paranOpened = false;
public static void run(int a[], int b) {
for (int i = 0; i < b - 1; i++) {
if (a[i] == a[i + 1]) {
if (!paranOpened) {
paranOpened = true;
System.out.print(" (");
}
System.out.print(a[i] + " ");
} else {
System.out.print(a[i] + " ");
if (paranOpened) {
System.out.print(") ");
paranOpened = false;
}
}
}// for loop

// print last item in array @(b-1)
System.out.print(a[b - 1] + " ");

// check if opened ( , then close it
if (paranOpened) {
System.out.print(") ");
}
}// run()

这是一个快速的解决方案,可能有更好的算法

关于java - 在数组中查找连续的重复整数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35681217/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com