Compare letter in java - java

I want to compare every letter on file 2 with file 1.
example :
file 1 : my name
file 2 : mi n#mes
i want to get the number of difference is 3, on file 2 : (i, #,and s).
Can you help me
Here is my code
public float getCER(String originalteks,String extractteks){
int end=0;
int start=0;
int different_char=0;
if(originalteks.length()!=extractteks.length()){
different_char=Math.abs(originalteks.length()-extractteks.length());
}
while(start<end){
if(originalteks.charAt(start)!=originalteks.charAt(start++))
different_char++;//jumlah diferent chart
}
return (float) different_char/originalteks.length();
}
And it's only counting the number of characters, not the different characters.

The following implementation tests for the total difference you need and is able to handle strings with different length, by comparing the shorter string to each substring of the longer up to the maximum offset of their difference. From those differences the smallest is chosen. Of course, if handleOffset is false, then we limit ourselves to only the start of the string and adding the difference to the result;
public int getCER(String originalteks,String extractteks, boolean handleOffset){
String shorter = originalteks;
String longer = extractteks;
if (shorter.length() > longer.length()) {
shorter = extractteks;
longer = originalteks;
}
int[] differences = new int[handleOffset ? (longer.length() - shorter.length + 1) : 1];
for (int i = 0; i < differences.length; i++) differences[i] = 0;
for (int i = 0; i < minLength; i++) {
for (j = 0; j < differences.length; j++) {
if (shorter.charAt(i) !== longer.charAt(i + j)) {
differences[j]++;
}
}
}
int min = shorter.length() + 1;
for (int i = 0; i < differences.length; i++) {
if (differences[i] < min) min = differences[i];
}
if (!handleOffset) min += longer.length() - shorter.length();
return min;
}

This should work for you. I just comment my changes within the example.
public int getCER(String originalteks,String extractteks){
int end;
int different_char=0;
//define the shorter end
if(originalteks.length < extractteks.length)
end = originalteks.length();
else
end = extractteks.length();
//no if needed -> same length, diff will be 0
different_char=Math.abs(originalteks.length()-extractteks.length());
for(int start = 0; start < end; start++){
if(originalteks.charAt(start)!=extractteks.charAt(start))
different_char++;//jumlah diferent chart
}
return different_char;
}

Related

How to reduce the number of loops if there is no change?

This code is radix sort in Java.
Now I can sort. But I want to reduce its functionality if there is no change in the
array, let it stop the loop and show the value.
Where do I have to fix it? Please guide me, thanks in advance.
public class RadixSort {
void countingSort(int inputArray[], int size, int place) {
//find largest element in input array at 'place'(unit,ten's etc)
int k = ((inputArray[0] / place) % 10);
for (int i = 1; i < size; i++) {
if (k < ((inputArray[i] / place) % 10)) {
k = ((inputArray[i] / place) % 10);
}
}
//initialize the count array of size (k+1) with all elements as 0.
int count[] = new int[k + 1];
for (int i = 0; i <= k; i++) {
count[i] = 0;
}
//Count the occurrence of each element of input array based on place value
//store the count at place value in count array.
for (int i = 0; i < size; i++) {
count[((inputArray[i] / place) % 10)]++;
}
//find cumulative(increased) sum in count array
for (int i = 1; i < (k + 1); i++) {
count[i] += count[i - 1];
}
//Store the elements from input array to output array using count array.
int outputArray[] = new int[size];
for (int j = (size - 1); j >= 0; j--) {
outputArray[count[((inputArray[j] / place) % 10)] - 1] = inputArray[j];
count[(inputArray[j] / place) % 10]--;//decrease count by one.
}
for (int i = 0; i < size; i++) {
inputArray[i] = outputArray[i];//copying output array to input array.
}
System.out.println(Arrays.toString(inputArray));
}
void radixSort(int inputArray[], int size) {
//find max element of inputArray
int max = inputArray[0];
for (int i = 1; i < size; i++) {
if (max < inputArray[i]) {
max = inputArray[i];
}
}
//find number of digits in max element
int d = 0;
while (max > 0) {
d++;
max /= 10;
}
//Use counting cort d no of times
int place = 1;//unit place
for (int i = 0; i < d; i++) {
System.out.print("iteration no = "+(i+1)+" ");
countingSort(inputArray, size, place);
place *= 10;//ten's , hundred's place etc
}
}
1
I'm going to resist typing out some code for you and instead go over the concepts since this looks like homework.
If I'm understanding you correctly, your problem boils down to: "I want to check if two arrays are equivalent and if they are, break out of a loop". Lets tackle the latter part first.
In Java, you can use the keyword"
break;
to break out of a loop.
A guide for checking if two arrays are equivalent in java can be found here:
https://www.geeksforgeeks.org/compare-two-arrays-java/
Sorry if this doesnt answer your question. Im just gonna suggest a faster way to find the digits of each element. Take the log base 10 of the element and add 1.
Like this : int digits = (int) Math.log10(i)+1;

Finding Similar Birthday through structure data

Hey guys I am trying to get the number of people who have the same birthday but this solution isn't working.This program is showing 0.0% .Please help me ...!.
public double calculate(int size, int count) {
int matches = 0;//initializing an integer variable
boolean out = false;
List<Integer> days=new ArrayList<Integer>();// creating arraylist name days of type int
for (int j = 0; j <count; j++) {
for (int i = 0; i < size; i++) {// initializing for loop till less than size
Random rand = new Random(); // creating an object of random function
int Brday = rand.nextInt(364) + 0;//initializing the limit of randomc number chozen
days.add(Brday); //adding values to arraylist
}
for (int l = 0; l < size; l++) {
int temp = l;//assigning value of l to a variable
for (int k = l + 1; k < size; k++) {
if (days.get(k) == temp) {// check statement to check values are same
matches++;//incrementing variable
out = true;
mOut.print("Count does have same birthday" + matches);
break;
} else {
mOut.print("does not have same birthday");
}
}
if (out) {
out = false;
break;
}
}
}
double prob = (double) matches / count;
mOut.print("The probability for two students to share a birthday is " + prob*100 + ".");
return prob;//returning double value of the function
}
Actually, you get either 0 percent or 100 percent with your code. Try invoking it with calculate(100, 100) if you want to see.
There are two things that are wrong in this code. First, if you run the simulation more than once (count > 1) then you never clear the list of birthdays before the second iteration.
Your method should begin with:
public double calculate(int size, int count) {
int matches = 0;
boolean out = false;
List<Integer> days;
for (int j = 0; j <count; j++) {
days = new ArrayList<Integer>();
Secondly, you're not comparing two birthdays but you're comparing a birthday to the index in the list.
This line:
int temp = l;//assigning value of l to a variable
Should read:
int temp = days.get(l); // Remember the birthday at index l
With those changes you'll get a much better result.

Calculating the maximum difference between two adjacent numbers in an array

Recently I've been assigned a task which asks to me to "calculate the maximum difference between two adjacent numbers in the array that is passed to it". I'm fairly new to Java (I have only done VB in the past) and since this topic was not well explained to me, I'm not quite sure how to go about it.
Here is some additional information about the task itself:
The function has to pass the following test. The function maxDiff should calculate the maximum difference between two adjacent numbers in the array that is passed to it.
#Test
public void assessmentTest() {
int [] numbers = {12, 8, 34, 10, 59};
assertEquals(49, maxDiff(numbers));
int [] numbers2 = {-50, 100, 20, -40};
assertEquals(150, maxDiff(numbers2));
}
You must assure to take the absolute difference, don't forget it. That's why I used the Math.abs() function.
public static int maxDiff(int[] numbers) {
int diff = Math.abs(numbers[1] - numbers[0]);
for(int i = 1; i < numbers.length-1; i++)
if(Math.abs(numbers[i+1]-numbers[i]) > diff)
diff = Math.abs(numbers[i+1] - numbers[i]);
return diff;
}
Something like this should do the trick:
public static int maxDiff(int[] numbers) {
if (numbers.length < 2) {
return 0;
}
if (numbers.length == 2) {
return Math.abs(numbers[1] - numbers[0]);
}
int max = Math.abs(numbers[1] - numbers[0]);
for (int i = 2; i < numbers.length; i++) {
int diff = Math.abs(numbers[i-1] - numbers[i]);
if (diff > max) {
max = diff;
}
}
return max;
}
For the specific question you asked:
public static int maxDiff(int[] arr) {
if(arr.length < 2)
return -1; // error condition: throw exception?
int maxdiff = Integer.MIN_VALUE;
for(int i = 1; i < arr.length; ++i) {
int diff = Math.abs(arr[i] - arr[i-1]);
if(diff > maxdiff)
maxdiff = diff;
}
return maxdiff;
}
If you want the max difference across all numbers in the array (not just adjacent ones) the most efficient way to do it would be to iterate the array just once to find the minimum and maximum, then return the absolute value of the two values subtracted from each other.
public static int maxDiff(int[] arr) {
if(arr.length < 2)
return -1; // error condition: throw exception?
int min = Integer.MAX_VALUE;
int max = Integer.MIN_VALUE;
for(int i = 0; i < arr.length; ++i) {
if(arr[i] < min)
min = arr[i];
if(arr[i] > max)
max = arr[i];
}
return Math.abs(max - min);
}
This piece of code can help you:
int[] numbers = {12, 8, 34, 10, 59};
int diff = 0;
int previous = 0;
for (int n : numbers) {
diff = Math.max(diff, Math.abs(n - previous));
previous = n;
}
Variable "diff" will contain the value you look for.
You can use this for Java;
int arrayMaximalAdjacentDifference(int[] inputArray) {
int max=0;
for( int i = 1 ; i < inputArray.length ; i++ ){
max = Math.max(max,Math.abs(inputArray[i] - inputArray[i-1]));
}
return max;
}

How to find the longest substring with equal amount of characters efficiently

I have a string that consists of characters A,B,C and D and I am trying to calculate the length of the longest substring that has an equal amount of each one of these characters in any order.
For example ABCDB would return 4, ABCC 0 and ADDBCCBA 8.
My code currently:
public int longestSubstring(String word) {
HashMap<Integer, String> map = new HashMap<Integer, String>();
for (int i = 0; i<word.length()-3; i++) {
map.put(i, word.substring(i, i+4));
}
StringBuilder sb;
int longest = 0;
for (int i = 0; i<map.size(); i++) {
sb = new StringBuilder();
sb.append(map.get(i));
int a = 4;
while (i<map.size()-a) {
sb.append(map.get(i+a));
a+= 4;
}
String substring = sb.toString();
if (equalAmountOfCharacters(substring)) {
int length = substring.length();
if (length > longest)
longest = length;
}
}
return longest;
}
This currently works pretty well if the string length is 10^4 but I'm trying to make it 10^5. Any tips or suggestions would be appreciated.
Let's assume that cnt(c, i) is the number of occurrences of the character c in the prefix of length i.
A substring (low, high] has an equal amount of two characters a and b iff cnt(a, high) - cnt(a, low) = cnt(b, high) - cnt(b, low), or, put it another way, cnt(b, high) - cnt(a, high) = cnt(b, low) - cnt(a, low). Thus, each position is described by a value of cnt(b, i) - cnt(a, i). Now we can generalize it for more that two characters: each position is described by a tuple (cnt(a_2, i) - cnt(a_1, i), ..., cnt(a_k, i) - cnt(a_1, i)), where a_1 ... a_k is the alphabet.
We can iterate over the given string and maintain the current tuple. At each step, we should update the answer by checking the value of i - first_occurrence(current_tuple), where first_occurrence is a hash table that stores the first occurrence of each tuple seen so far. Do not forget to put a tuple of zeros to the hash map before iteration(it corresponds to an empty prefix).
If there were only A's and B's, then you could do something like this.
def longest_balanced(word):
length = 0
cumulative_difference = 0
first_index = {0: -1}
for index, letter in enumerate(word):
if letter == 'A':
cumulative_difference += 1
elif letter == 'B':
cumulative_difference -= 1
else:
raise ValueError(letter)
if cumulative_difference in first_index:
length = max(length, index - first_index[cumulative_difference])
else:
first_index[cumulative_difference] = index
return length
Life is more complicated with all four letters, but the idea is much the same. Instead of keeping just one cumulative difference, for A's versus B's, we keep three, for A's versus B's, A's versus C's, and A's versus D's.
Well, first of all abstain from constructing any strings.
If you don't produce any (or nearly no) garbage, there's no need to collect it, which is a major plus.
Next, use a different data-structure:
I suggest 4 byte-arrays, storing the count of their respective symbol in the 4-span starting at the corresponding string-index.
That should speed it up considerably.
You can count the occurrences of the characters in word. Then, a possible solution could be:
If min is the minimum number of occurrences of any character in word, then min is also the maximum possible number of occurrences of each character in the substring we are looking for. In the code below, min is maxCount.
We iterate over decreasing values of maxCount. At every step, the string we are searching for will have length maxCount * alphabetSize. We can view this as the size of a sliding window we can slide over word.
We slide the window over word, counting the occurrences of the characters in the window. If the window is the substring we are searching for, we return the result. Otherwise, we keep searching.
[FIXED] The code:
private static final int ALPHABET_SIZE = 4;
public int longestSubstring(String word) {
// count
int[] count = new int[ALPHABET_SIZE];
for (int i = 0; i < word.length(); i++) {
char c = word.charAt(i);
count[c - 'A']++;
}
int maxCount = word.length();
for (int i = 0; i < count.length; i++) {
int cnt = count[i];
if (cnt < maxCount) {
maxCount = cnt;
}
}
// iterate over maxCount until found
boolean found = false;
while (maxCount > 0 && !found) {
int substringLength = maxCount * ALPHABET_SIZE;
found = findSubstring(substringLength, word, maxCount);
if (!found) {
maxCount--;
}
}
return found ? maxCount * ALPHABET_SIZE : 0;
}
private boolean findSubstring(int length, String word, int maxCount) {
int startIndex = 0;
boolean found = false;
while (startIndex + length <= word.length()) {
int[] count = new int[ALPHABET_SIZE];
for (int i = startIndex; i < startIndex + length; i++) {
char c = word.charAt(i);
int cnt = ++count[c - 'A'];
if (cnt > maxCount) {
break;
}
}
if (equalValues(count, maxCount)) {
found = true;
break;
} else {
startIndex++;
}
}
return found;
}
// Returns true if all values in c are equal to value
private boolean equalValues(int[] count, int value) {
boolean result = true;
for (int i : count) {
if (i != value) {
result = false;
break;
}
}
return result;
}
[MERGED] This is Hollis Waite's solution using cumulative counts, but taking my observations at points 1. and 2. into consideration. This may improve performance for some inputs:
private static final int ALPHABET_SIZE = 4;
public int longestSubstring(String word) {
// count
int[][] cumulativeCount = new int[ALPHABET_SIZE][];
for (int i = 0; i < ALPHABET_SIZE; i++) {
cumulativeCount[i] = new int[word.length() + 1];
}
int[] count = new int[ALPHABET_SIZE];
for (int i = 0; i < word.length(); i++) {
char c = word.charAt(i);
count[c - 'A']++;
for (int j = 0; j < ALPHABET_SIZE; j++) {
cumulativeCount[j][i + 1] = count[j];
}
}
int maxCount = word.length();
for (int i = 0; i < count.length; i++) {
int cnt = count[i];
if (cnt < maxCount) {
maxCount = cnt;
}
}
// iterate over maxCount until found
boolean found = false;
while (maxCount > 0 && !found) {
int substringLength = maxCount * ALPHABET_SIZE;
found = findSubstring(substringLength, word, maxCount, cumulativeCount);
if (!found) {
maxCount--;
}
}
return found ? maxCount * ALPHABET_SIZE : 0;
}
private boolean findSubstring(int length, String word, int maxCount, int[][] cumulativeCount) {
int startIndex = 0;
int endIndex = (startIndex + length) - 1;
boolean found = true;
while (endIndex < word.length()) {
for (int i = 0; i < ALPHABET_SIZE; i++) {
if (cumulativeCount[i][endIndex] - cumulativeCount[i][startIndex] != maxCount) {
found = false;
break;
}
}
if (found) {
break;
} else {
startIndex++;
endIndex++;
}
}
return found;
}
You'll probably want to cache cumulative counts of characters for each index of String -- that's where the real bottleneck is. Haven't thoroughly tested but something like the below should work.
public class Test {
static final int LEN = 4;
static class RandomCharSequence implements CharSequence {
private final Random mRandom = new Random();
private final int mAlphabetLen;
private final int mLen;
private final int mOffset;
RandomCharSequence(int pLen, int pOffset, int pAlphabetLen) {
mAlphabetLen = pAlphabetLen;
mLen = pLen;
mOffset = pOffset;
}
public int length() {return mLen;}
public char charAt(int pIdx) {
mRandom.setSeed(mOffset + pIdx);
return (char) (
'A' +
(mRandom.nextInt() % mAlphabetLen + mAlphabetLen) % mAlphabetLen
);
}
public CharSequence subSequence(int pStart, int pEnd) {
return new RandomCharSequence(pEnd - pStart, pStart, mAlphabetLen);
}
#Override public String toString() {
return (new StringBuilder(this)).toString();
}
}
public static void main(String[] pArgs) {
Stream.of("ABCDB", "ABCC", "ADDBCCBA", "DADDBCCBA").forEach(
pWord -> System.out.println(longestSubstring(pWord))
);
for (int i = 0; ; i++) {
final double len = Math.pow(10, i);
if (len >= Integer.MAX_VALUE) break;
System.out.println("Str len 10^" + i);
for (int alphabetLen = 1; alphabetLen <= LEN; alphabetLen++) {
final Instant start = Instant.now();
final int val = longestSubstring(
new RandomCharSequence((int) len, 0, alphabetLen)
);
System.out.println(
String.format(
" alphabet len %d; result %08d; time %s",
alphabetLen,
val,
formatMillis(ChronoUnit.MILLIS.between(start, Instant.now()))
)
);
}
}
}
static String formatMillis(long millis) {
return String.format(
"%d:%02d:%02d.%03d",
TimeUnit.MILLISECONDS.toHours(millis),
TimeUnit.MILLISECONDS.toMinutes(millis) -
TimeUnit.HOURS.toMinutes(TimeUnit.MILLISECONDS.toHours(millis)),
TimeUnit.MILLISECONDS.toSeconds(millis) -
TimeUnit.MINUTES.toSeconds(TimeUnit.MILLISECONDS.toMinutes(millis)),
TimeUnit.MILLISECONDS.toMillis(millis) -
TimeUnit.SECONDS.toMillis(TimeUnit.MILLISECONDS.toSeconds(millis))
);
}
static int longestSubstring(CharSequence pWord) {
// create array that stores cumulative char counts at each index of string
// idx 0 = char (A-D); idx 1 = offset
final int[][] cumulativeCnts = new int[LEN][];
for (int i = 0; i < LEN; i++) {
cumulativeCnts[i] = new int[pWord.length() + 1];
}
final int[] cumulativeCnt = new int[LEN];
for (int i = 0; i < pWord.length(); i++) {
cumulativeCnt[pWord.charAt(i) - 'A']++;
for (int j = 0; j < LEN; j++) {
cumulativeCnts[j][i + 1] = cumulativeCnt[j];
}
}
final int maxResult = Arrays.stream(cumulativeCnt).min().orElse(0) * LEN;
if (maxResult == 0) return 0;
int result = 0;
for (int initialOffset = 0; initialOffset < LEN; initialOffset++) {
for (
int start = initialOffset;
start < pWord.length() - result;
start += LEN
) {
endLoop:
for (
int end = start + result + LEN;
end <= pWord.length() && end - start <= maxResult;
end += LEN
) {
final int substrLen = end - start;
final int expectedCharCnt = substrLen / LEN;
for (int i = 0; i < LEN; i++) {
if (
cumulativeCnts[i][end] - cumulativeCnts[i][start] !=
expectedCharCnt
) {
continue endLoop;
}
}
if (substrLen > result) result = substrLen;
}
}
}
return result;
}
}
Suppose there are K possible letters in a string of length N. We could track the balance of letters seen with a vector pos of length K that is updated as follows:
If letter 1 is seen, add (K-1, -1, -1, ...)
If letter 2 is seen, add (-1, K-1, -1, ...)
If letter 3 is seen, add (-1, -1, K-1, ...)
Maintain a hash that maps pos to the first string position where pos is reached. Balanced substrings occur whenever hash[pos] already exists and the substring value is s[hash[pos]:pos].
The cost of maintaining the hash is O(log N) so processing the string takes O(N log N). How does this compare with solutions so far? These types of problems tend to have linear solutions but I haven't come across one yet.
Here's some code demonstrating the idea for 3 letters and a run using biased random strings. (Uniform random strings allow for solutions that are around half the string length, which is unwieldy to print).
#!/usr/bin/python
import random
from time import time
alphabet = "abc"
DIM = len(alphabet)
def random_string(n):
# return a random string over choices[] of length n
# distribution of letters is non-uniform to make matches harder to find
choices = "aabbc"
s = ''
for i in range(n):
r = random.randint(0, len(choices) - 1)
s += choices[r]
return s
def validate(s):
# verify frequencies of each letter are the same
f = [0, 0, 0]
a2f = {alphabet[i] : i for i in range(DIM)}
for c in s:
f[a2f[c]] += 1
assert f[0] == f[1] and f[1] == f[2]
def longest_balanced(s):
"""return length of longest substring of s containing equal
populations of each letter in alphabet"""
slen = len(s)
p = [0 for i in range(DIM)]
vec = {alphabet[0] : [2, -1, -1],
alphabet[1] : [-1, 2, -1],
alphabet[2] : [-1, -1, 2]}
x = -1
best = -1
hist = {str([0, 0, 0]) : -1}
for c in s:
x += 1
p = [p[i] + vec[c][i] for i in range(DIM)]
pkey = str(p)
if pkey not in hist:
hist[pkey] = x
else:
span = x - hist[pkey]
assert span % DIM == 0
if span > best:
best = span
cand = s[hist[pkey] + 1: x + 1]
print("best so far %d = [%d,%d]: %s" % (best,
hist[pkey] + 1,
x + 1,
cand))
validate(cand)
return best if best > -1 else 0
def main():
#print longest_balanced( "aaabcabcbbcc" )
t0 = time()
s = random_string(1000000)
print "generate time:", time() - t0
t1 = time()
best = longest_balanced( s )
print "best:", best
print "elapsed:", time() - t1
main()
Sample run on an input of 10^6 letters with an alphabet of 3 letters:
$ ./bal.py
...
best so far 189 = [847894,848083]: aacacbcbabbbcabaabbbaabbbaaaacbcaaaccccbcbcbababaabbccccbbabbacabbbbbcaacacccbbaacbabcbccaabaccabbbbbababbacbaaaacabcbabcbccbabbccaccaabbcabaabccccaacccccbaacaaaccbbcbcabcbcacaabccbacccacca
best: 189
elapsed: 1.43609690666

How do I trim the leading zeros in an array of digits without using an arraylist in java?

I have an array made that represents digits and I am trying to make a method so that if there are zeros in front of the first significant digit I want to trim them, I understand you can't re size arrays so I have created a new array, but my code doesn't seem to run correctly?
Here is my code I can't figure out what is wrong I've tried everything: (I put stars around the error** It gives an arrayoutofbounds error **)
package music;
import java.util.Random;
/**Music Array
*
* #author Ryan Klotz
* #version February 3, 2015
*/
public class Music
{
private int length; // length of the array
private int numOfDigits; // number of actual digits in the array
int[] musicArray;
/**Explicit Constructor
* #param x The length of the array
*/
public Music(int x)
{
length = x;
musicArray = new int[length];
Random rand = new Random();
numOfDigits = rand.nextInt(length);
int posOrNeg; // determines positive or negative sign
int digit;
for (int i = 0; i <= numOfDigits; i++)
{
digit = rand.nextInt(10);
posOrNeg = rand.nextInt(2);
if (posOrNeg == 0)
{
digit *= -1;
musicArray[i] = digit;
}
else
{
musicArray[i] = digit;
}
}
}
public void trimLeadingSilence(Music x)
{
while (x.musicArray[0] == 0)
{
int[] newMusicArray;
int count = 0;
**while (x.musicArray[count] == 0)**
{
count++;
}
if (count == x.numOfDigits)
{
newMusicArray = new int[1];
newMusicArray[0] = 0;
x.numOfDigits = 1;
x.musicArray = newMusicArray;
}
else
{
newMusicArray = new int[x.numOfDigits - count];
for (int i = 0; i <= x.numOfDigits - count; i++)
{
newMusicArray[i] = x.musicArray[i + count];
}
x.numOfDigits -= count;
x.musicArray = newMusicArray;
}
}
}
}
i <= x.numOfDigits - count should use < instead. But Arrays.copyOfRange is probably a better solution.
for (int i = 0; i <= numOfDigits; i++)
Should be
for (int i = 0; i < numOfDigits; i++)
Currently you are generating 1 more digit than numOfDigits is. This will not give you any exceptions in any case since randInt(length) will be in range of 0 and length - 1.
while (x.musicArray[count] == 0)
{
count++;
}
Will throw an exception if all values in array are 0.
while (count < x.musicArray.length && x.musicArray[count] == 0){
count++;
}
Will fix that for you.
for (int i = 0; i <= x.numOfDigits - count; i++)
Will also throw you ArrayIndexOutOfBoundsException so you should fix it to:
for (int i = 0; i < x.numOfDigits - count; i++)
Anyway, this is very inefficient since if you have 10 "0" values at the start you are creating 10 new arrays. Take a look at Arrays.copyOfRange method, you should be able to do the same job in less than 10 lines of code.
Inside your for loop, use i < x.numOfDigits - count (you were using <=).
That will solve the problem.

Categories