[英]How do i fix my interpretation of this run-length encoding algorithm?
對於學校,我必須在Java中構建一個使用RLE(行程編碼)壓縮數組的方法。 我找不到在線解決方案,因為我的老師要我自己解決問題。 不幸的是,我無法做到這一點,因為我是一個忙碌的人,有一些忙碌的計划。
RLE將此轉換為:{1,1,1,1,2,2,3,3,6,6,6,7,8,8,8}轉換為:{4,1,2,2,2,3 ,3,6,1,7,3,8}它基本上構成一個新數組,該數組遵循以下公式{此值的#,此值,此值的#,此值,續...}有4個1 {4,1}你得到我的認可。
這是我嘗試做的事情(請原諒我糟糕的代碼,我只是一名高中生):
public class tester{
public static void main(String[] args){
int[] potato = {1,1,1,2,2,4,4,4,6,6,6,6};
printArray(compress(potato));
}
public static void printArray(int[] arr){
for(int i = 0; i < arr.length; i++){
System.out.println(arr[i]);
}
}
public static int[] compress(int[] a) {
//figure out how many different numbers there are.
int diffNums = 1;
for(int i = 0; i < a.length; i++){
if(i != a.length-1 && a[i] != a[i+1]){
diffNums++;
}
}
//make compressed array at the correct length.
int[] compressed = new int[diffNums * 2];
//figure out what each number is.
int[] nums = new int[diffNums];
nums[0] = a[0];
int spot = 0;
for(int i = 0; i < a.length; i++){
if(i != a.length-1 && a[i] != a[i+1]){
nums[spot] = a[i+1];
}
}
//figure out quantity of each number.
int[] quantities = new int[diffNums];
int spot2 = 0;
int spotcur = 0;
for(int i = 0; i < diffNums; i++){
int quant = 0;
while(a[spotcur] == a[spot2]){
quant++;
spotcur++;
}
spot2 = spotcur;
quantities[i] = quant;
}
//add them together and return compressed array
int spotter = 0;
for(int i = 0; i < diffNums; i++){
compressed[spotter] = quantities[i];
spotter++;
compressed[spotter] = nums[i];
spotter++;
}
return compressed;
}
}
有誰知道我該如何解決這個糟糕的代碼? 我被困在上面
我認為可以用更少的代碼來解決這個問題。 您可以使用外部/內部循環構造,如下所示:
public static int[] compress(int[] a) {
List<Integer> encoded = new ArrayList<>();
for (int i=0; i<a.length; i++) {
int num = a[i];
int count = 1;
for (int j=i+1; j<a.length; j++) {
int nextNum = a[j];
if (nextNum != num)
break;
count++;
i++;
}
encoded.add(count);
encoded.add(num);
}
return encoded.stream().mapToInt(i->i).toArray();
}
另外, Arrays類包含一個已經定義的有用的toString方法。
System.out.println(Arrays.toString(compress(potato)));
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.