Java Homework help: Compress Sparse Array. Can someone help me with the followin
ID: 3831430 • Letter: J
Question
Java Homework help: Compress Sparse Array. Can someone help me with the following question?
/*
Please complete the following `SparseCompression` compression method to compress a sparse array.
**Assume that the sparse array only contains one non-zero integer and always starts with 0.**
Note: the input of the method is an `int[] array` and the output of the method is a `String`. (5 points)
For example:
input:
int[] array = {0, 0, 0, 0, 0, 0, 0, 999};
Output:
"#7, 999,"
input:
int[] array = {0, 0, 0, 1};
Output:
"#3, 1,"
*/
public class Compress
{
public static void main(String[] args)
{
int[] test = {0, 0, 0, 0, 0, 0, 0, 999};
String result = SparseCompression(test);
// expected result: "#7,999,"
System.out.println(result);
}
public static String SparseCompression(int[] array)
{
// Your code goes here
String result = "#6,3";
return result;
}
}
Explanation / Answer
public class Compress
{
public static void main(String[] args)
{
int[] test = {0, 0, 0, 0, 0, 0, 0, 999,0};
String result = SparseCompression(test);
// expected result: "#7,999,"
System.out.println(result);
}
public static String SparseCompression(int[] array)
{
// Your code goes here
int z=0;
int len = array.length;
int pos=0;
for(int i=0;i<len;i++)
{
if(array[i]!=0)
{
pos=i;
break;
}
}
String result = "#6,3";
result = "#"+(pos)+", "+array[pos]+",";
if(len-pos-1>0)
{
result = result + " #"+(len-1-pos)+",";
}
return result;
}
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.