gpt4 book ai didi

java - 从另一个数组创建一个数组?

转载 作者:行者123 更新时间:2023-12-02 08:54:19 25 4
gpt4 key购买 nike

java新手,正在使用RLE编码,我正在尝试创建一个程序,该程序接受一个字节数组,然后返回另一个字节数组,但它接受数组中连续值的数量,然后打印[(重复次数),(值)]。例如,[ 13,13,13,3,3,3,3 ] 将返回 [3,13,4,3]

import java.util.Arrays;

public class testing {

public static void main(String [] args) {

byte [] pracArray = {13,13,13,3,3,3,3};

int count = 1;

for (int i = 0; i <pracArray.length-1; i++)
{
if (pracArray[i] != pracArray[i+1])
{
count++;
}
}

byte numLength = 1;
byte indexNum = 0;
int newArraySize = count*2;

byte [] newArray = new byte [newArraySize];

for ( int i = 0; i < pracArray.length-1; i++)
{
if (pracArray[i] != pracArray[i+1] )
{
newArray[indexNum] = numLength;
newArray[indexNum+1] = pracArray[i];
indexNum = (byte) (indexNum + 2);
numLength = 1;
}
else
{
numLength++;
}
}
System.out.println(Arrays.toString((pracArray)));
System.out.println(Arrays.toString((newArray)));
}
}

我知道我的问题,最后运行的连续数字没有被打印。如果我将数组更改为 [13,13,13,3,3,3,3,1] 它将打印 [3,13,4,3,0,0],最后一个数字序列永远不会被记录,因此newArray 的最后两个值永远不会被填充。关于如何更改 if 语句以包含最后的数字序列有什么想法吗?

最佳答案

循环终止时,检查最后一个元素是否等于倒数第二个元素。

您的更新代码将是:

import java.util.Arrays;

public class Main {
public static void main(String[] args) {

byte[] pracArray = { 13, 13, 13, 3, 3, 3, 3, 1 };

int count = 1;

for (int i = 0; i < pracArray.length - 1; i++) {
if (pracArray[i] != pracArray[i + 1]) {
count++;
}
}

byte numLength = 1;
byte indexNum = 0;
int newArraySize = count * 2;

byte[] newArray = new byte[newArraySize];
int i;
for (i = 0; i < pracArray.length - 1; i++) {
if (pracArray[i] != pracArray[i + 1]) {
newArray[indexNum] = numLength;
newArray[indexNum + 1] = pracArray[i];
indexNum = (byte) (indexNum + 2);
numLength = 1;
} else {
numLength++;
}
}
if (pracArray[i - 1] == pracArray[i]) {
newArray[indexNum] = numLength;
newArray[indexNum + 1] = pracArray[i];
indexNum = (byte) (indexNum + 2);
numLength = 1;
} else {
newArray[indexNum] = numLength;
newArray[indexNum + 1] = pracArray[i];
}

System.out.println(Arrays.toString((pracArray)));
System.out.println(Arrays.toString((newArray)));
}
}

输出:

[13, 13, 13, 3, 3, 3, 3, 1]
[3, 13, 4, 3, 1, 1]

byte[] pracArray = { 13, 13, 13, 3, 3, 3, 3 } 的输出如下:

[13, 13, 13, 3, 3, 3, 3]
[3, 13, 4, 3]

关于java - 从另一个数组创建一个数组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60582538/

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