Duplicates in a sorted java array - java

I have to write a method that takes an array of ints that is already sorted in numerical order then remove all the duplicate numbers and return an array of just the numbers that have no duplicates. That array must then be printed out so I can't have any null pointer exceptions. The method has to be in O(n) time, can't use vectors or hashes. This is what I have so far but it only has the first couple numbers in order without duplicates and then just puts the duplicates in the back of the array. I can't create a temporary array because it gives me null pointer exceptions.
public static int[] noDups(int[] myArray) {
int j = 0;
for (int i = 1; i < myArray.length; i++) {
if (myArray[i] != myArray[j]) {
j++;
myArray[j] = myArray[i];
}
}
return myArray;
}

Since this seems to be homework I don't want to give you the exact code, but here's what to do:
Do a first run through of the array to see how many duplicates there are
Create a new array of size (oldSize - duplicates)
Do another run through of the array to put the unique values in the new array
Since the array is sorted, you can just check if array[n] == array[n+1]. If not, then it isn't a duplicate. Be careful about your array bounds when checking n+1.
edit: because this involves two run throughs it will run in O(2n) -> O(n) time.

Tested and works (assuming the array is ordered already)
public static int[] noDups(int[] myArray) {
int dups = 0; // represents number of duplicate numbers
for (int i = 1; i < myArray.length; i++)
{
// if number in array after current number in array is the same
if (myArray[i] == myArray[i - 1])
dups++; // add one to number of duplicates
}
// create return array (with no duplicates)
// and subtract the number of duplicates from the original size (no NPEs)
int[] returnArray = new int[myArray.length - dups];
returnArray[0] = myArray[0]; // set the first positions equal to each other
// because it's not iterated over in the loop
int count = 1; // element count for the return array
for (int i = 1; i < myArray.length; i++)
{
// if current number in original array is not the same as the one before
if (myArray[i] != myArray[i-1])
{
returnArray[count] = myArray[i]; // add the number to the return array
count++; // continue to next element in the return array
}
}
return returnArray; // return the ordered, unique array
}
My previous answer to this problem with used an Integer List.

Not creating a new array will surely result in nulls all over the initial array. Therefore create a new array for storing the unique values from the initial array.
How do you check for unique values? Here's the pseudo code
uniq = null
loop(1..arraysize)
if (array[current] == uniq) skip
else store array[current] in next free index of new array; uniq = array[current]
end loop
Also as others mentioned get the array size by initial scan of array
uniq = null
count = 0
loop(1..arraysize)
if (array[current] == uniq) skip
else uniq = array[current] and count++
end loop
create new array of size count

public static int[] findDups(int[] myArray) {
int numOfDups = 0;
for (int i = 0; i < myArray.length-1; i++) {
if (myArray[i] == myArray[i+1]) {
numOfDups++;
}
}
int[] noDupArray = new int[myArray.length-numOfDups];
int last = 0;
int x = 0;
for (int i = 0; i < myArray.length; i++) {
if(last!=myArray[i]) {
last = myArray[i];
noDupArray[x++] = last;
}
}
return noDupArray;
}

public int[] noDups(int[] arr){
int j = 0;
// copy the items without the dups to res
int[] res = new int[arr.length];
for(int i=0; i<arr.length-2; i++){
if(arr[i] != arr[i+1]){
res[j] = arr[i];
j++;
}
}
// copy the last element
res[j]=arr[arr.length-1];
j++;
// now move the result into a compact array (exact size)
int[] ans = new int[j];
for(int i=0; i<j; i++){
ans[i] = res[i];
}
return ans;
}
First loop is O(n) and so is the second loop - which totals in O(n) as requested.

Related

This code adds the same "myRndmNos" array twice. but i want it to add the unsorted "myRndmNos" and the sorted "bubblesorted" array. How do i get it?

when i try to add the two arrays that I generated from random numbers and the sorted, it just add the unsorted array twice. what am i missing?
boolean sorted = false;
int temp;
while (!sorted) {
sorted = true;
for (int i = 0; i < myRndmNos.length - 1; i++) {
if (myRndmNos[i] > myRndmNos[i+1]) {
temp = myRndmNos[i];
myRndmNos[i] = myRndmNos[i+1];
myRndmNos[i+1] = temp;
sorted = false;
}
}
}
i think this part is wrong
for (int j = 0; j < myRndmNos.length; j++){
bubblesorted[j] = myRndmNos[j];
}
System.out.println("Sorted");
System.out.println(Arrays.toString(bubblesorted));
if(myRndmNos.length == bubblesorted.length)
{
for (int k = 0; k < myRndmNos.length; k++)
{
arraySum[k] = myRndmNos[k] + bubblesorted[k];
}
System.out.println("Element-wise added two arrays");
System.out.println(Arrays.toString(arraySum));
}
else
{
System.out.println("Two arrays are not equal");
}
}
}
Are you doing the sorting before assigning the value to the new bubblesorted array or after it ?
Looking at the code, It looks like you have sorted the array , and then assigning the same values to bubblesorted array. This results in addition of same element in the array.
I would suggest to create both the array first, and then go for the sorting and adding functionality.

How to return only needed values without 0's and nulls in this question?

I have this question that I have been tackling for a while.
"The method should return an array containing the elements that are divisible by a certain number" in this case the target which is 5.
Here is my solution
public static int[] Divisible(int[] array, int target){
int[] answer = new int[array.length];
for (int i = 0; i<array.length; i++){
if (array[i] % target == 0){
answer[i] = array[i];
}
}
return answer;
}
assuming my input is
int[] input = {5,3,6,10};
my output will be [5,0,0,10].
My desired output should be [5,10].
please, How do I get rid of the zeros
The basic idea is to fill the answer array from the bottom, and then truncate it to exactly the size you need.
int j = 0;
for (int i=0; i<array.length; i++) {
if (array[i] % target == 0){
answer[j++] = array[i];
}
}
return Arrays.copyOf(answer, j);
Arrays is a standard Java utility class.
If you're not allowed to use the Arrays utility class then the last line can be replaced by:
int[] answer2 = new int[j];
for (int i=0; i<j; i++)
answer2[i] = answer[i];
return answer2;
This feels a little clunky to me but it satisfies the apparent requirements to use simple arrays.
you can do like this
public static int[] Divisible(int[] array, int target){
List<Integer> list = new ArrayList<>();
for (int i = 0; i<array.length; i++){
if (array[i] % target == 0){
list.add(array[i]);
}
}
int[] ints = new int[list.size()];
for (int i = 0; i < ints.length; i++) {
ints[i] = list.get(i);
}
return ints;
}
Two options:
you can use an ArrayList internally, as that can grow dynamically (you just keep adding the values you are interested in, done). If you have to return an array, you can easily do that based on your filled list.
when going only with arrays you can simply do 2 passes: first create that large array and fill it. Then count the non zero entries! Create a new array with the smaller length, and then copy over all non zero elements manually.
I have used the method stated by #GhostCat but it made me change the code entirely. This is my new code
public static Object[] Divisi(int[] array, int target){
ArrayList<Integer> answer = new ArrayList<>();
for (int i = 0; i<array.length; i++){
if (array[i] % target == 0){
answer.add(array[i]);
}
}
return answer.toArray();
}
This gave me the desired answer but how else can i do this without converting to object
The shortest and the most quickest way to go about this is, you can change the array to an ArrayList and then use .toArray() method to get it back as a primitive array when returning.
public static Integer[] Divisible(int[] array, int target){
List<Integer> answer = new ArrayList<>();
for (int i = 0; i<array.length; i++){
if (array[i] % target == 0) {
answer.add(array[i]); // pushing to list only if the number is divisible
}
}
return answer.toArray(new Integer[0]); // converting the list to an array before returning
}
If you want a list of unique numbers use Set instead of a List.
Set<Integer> answer = new HashSet<>();
Instead of using the primitive int, I have conformed to using Integer instead.
Here is my solution.
public static Integer[] divisible(Integer[] array, int target) {
int j = 0;
ArrayList<Integer> list = new ArrayList<Integer>();
for (int i = 0; i < array.length; i++) {
if (array[i] % target == 0) {
j++;
list.add(array[i]);
}
}
Integer answer[] = new Integer[j];
answer = list.toArray(answer);
return answer;
}
You should use a separate counter for the result array and keep incrementing the counter if the number is divisible by the target.
Something like this :
int[] result=new int[array.length];
int resultindex=0; //create a separate counter
for(int i=0;i<array.length;i++)
{
if(array[i]%target==0)
{
result[resultindex]=array[i];
++resultindex; //update the counter
}
}

How to find permutations of array of ints with java

I am doing some practice where I have to find all the permutations of n numbers. I was given pseudo code, however, I am having difficulties translating it.
public void nextPerm(int[] a,int pivot,int suc){
suc = 0;
pivot = 0;
for(int i = a.length-1;; i--){
if( i+1 != a.length)
if(a[i] < a[i+1]){
pivot = i;
break;
} else if(pivot == 0){
reverseArray(a,pivot);//this just reverses the array from the right of the pivot point
System.out.println(a);
}
}
for(int i = a.length-1;;i--){
if(a[i] > a[pivot]){
suc = i;
break;
}
}
//swap pivot and suc
int place = a[pivot];
a[pivot] = a[suc];
a[place] = a[pivot];
reverseArray(a,pivot);
System.out.println(Arrays.toString(a));
}
private void reverseArray(int[] a,int pivot) {//make pivot the index which it will reverse to the right of
// TODO Auto-generated method stub
int[] place = new int[a.length-pivot-1];
int counter = 0;
for(int i = a.length-1; i > pivot;i--){
place[counter] = a[i];
counter++;
}
counter = 0;
int[] hold = new int[a.length];
for(int i = 0; i <= pivot;i++){
hold[i] = a[i];
counter++;
}
for(int i = 0; i < place.length;i++){
hold[counter] = place[i];
counter++;
}
System.out.println(Arrays.toString(hold));
}
This is what I have so far. Basically each time I run nextPerm it adjusts an array to be another permutation. For more info check out the pages here: link to more info
Summary: nextPerm finds all the possible perms one at a time by manually changing the array.
You just need to pass the output obtained in previous step as input to next step until you iterate over all possible permutations. Here is an explanation and pseudo code for the same.
Lets say that you have an array [1,2,3,4]. Total permutations possible with 4 elements in array would be 4! assuming all elements are distinct. So, just iterate the above code for nextPerm 4! times.
int fact = factorial(array.length);
for(int i = 0;i<fact;i++){
int[] b = nextPerm(array);
array = b;
}
assuming that your nextPrem returns you the next permutated array.

How can I count and print duplicate strings in a string array in Java?

I have a dilemma on my hands. After much trial and error, I still could not figure out this simple task.
I have one array
String [] array = {anps, anps, anps, bbo, ehllo};
I need to be able to go through the array and find duplicates and print them on the same line. Words with no duplicates should be displayed alone
The output needs to be like this
anps anps anps
bbo
ehllo
I have tried while, for loops but the logic seems impossible.
Okay, there are a worryingly number of either wrong answers or answers that use HashMap or HashSet for this very simple iteration problem, so here is a correct solution.
Arrays.sort(array);
for (int i = 0; i < array.length; ++i){
if (i+1 == array.length) {
System.out.println(array[i]);
} else if (array[i].equals(array[i+1])) {
System.out.print(array[i]+" ");
} else {
System.out.println(array[i]);
}
}
Sort the array first then
for(int i = 0, i < array.length; i++){
String temp = array[i];
System.out.print(temp+" ");
for(int j = i+1; j < array.length; j++){
String temp2 = array[j];
if(temp.compareTo(temp2) == 0){
System.out.print(temp2+" ");
i++;
}
}
System.out.println();
}
or something similar...
There are multiple ways of achieving this.
Use two for loops, one that loops through the array and picks a value and another inner loop where you go through the array (from the current index) looking for that value
You could have a map that contains the words, you loop through the array and you fill out the map with the number of occurrences corresponding to the value currently fetched from the array
The second way is better. The code is something like:
Map<String, Integer> occurences = new HashMap<String, Integer>();
for(int index=0; index < array.length; index++){
int nOcc = 1;
if(occurences.containsKey(array[index]){
nOcc = occurences.get(array[index]) + 1;
}
occurences.remove(array[index]);
occurences.put(array[index], nOcc);
}
At this point, the map should contain all words (keys) and their corresponding number of occurrences (values)
If you sort the array first, then you can just check if the current index is equal to the next index (bearing in mind that you must account for IndexOutOfBounds), if they are equal do a System.out.print() if they are not equal do a System.Out.println().
String [] array = {"anps", "anps", "anps", "bbo", "ehllo"};
// If you already are assured that the strings in the array are sorted
// then the sort is not necessary.
Arrays.sort(array);
for(int i = 0; i < array.length; i++){
if((i+1)==array.length || !array[i].equals(array[(i+1)])){
System.out.println(array[i]);
} else {
System.out.print(array[i]+" ");
}
}
Complexity n^2 , just start from first value and go to the end finding the same, if you found print in one line and go to the new line, also you should delete all printed value.
Complexity nlogn + n == nlogn , merge or quick sort, and after this go to the end and pring sequenced values.
There are more solutions but I think its enough for you.
Naive Algorithms
Create a Map
Iterate through all array
check if key already exist in map
if yes update value +1
if no insert
print the map as you want
You should be able to do what you're looking for !
Use below logic
import java.util.ArrayList;
public class RepeatStringPrint {
/**
* #param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
try {
String[] x = { "anps", "anps", "anps", "bbo", "ehllo" };
String total[] = new String[50];
String sTotal[] = null;
for (int i = 0; i < x.length; i++) {
total[i] = x[i];
}
for (int k = 0; k < total.length; k++) {
int count = 0;
if (total[k] != null) {
sTotal = new String[50];
for (int i = 0; i < total.length; i++) {
if (total[k] == total[i]) {
count++;
if (count <= 1) {
sTotal[i] = total[k];
}
}
}
if (sTotal[k] != null) {
for(int j=0; j<count; j++){
System.out.print(sTotal[k]+"\t");
}
System.out.print("\n");
}
}
}
}
catch (Exception e) {
}
}
}

Find the mode (most frequent value in an array) using a simple for loop?

How do I find the mode (most frequent value in an array) using a simple for loop?
The code compiles with a wrong output.
Here is what I have:
public static void mode(double [] arr)
{
double mode=arr[0];
for(int i = 1; i<arr.length; i++)
{
if(mode==arr[i])
{
mode++;
}
}
return mode;
}
First I sort the array by order and then I count occurrences of one number. No hashmaps only for loop and if statements.
My code:
static int Mode(int[] n){
int t = 0;
for(int i=0; i<n.length; i++){
for(int j=1; j<n.length-i; j++){
if(n[j-1] > n[j]){
t = n[j-1];
n[j-1] = n[j];
n[j] = t;
}
}
}
int mode = n[0];
int temp = 1;
int temp2 = 1;
for(int i=1;i<n.length;i++){
if(n[i-1] == n[i]){
temp++;
}
else {
temp = 1;
}
if(temp >= temp2){
mode = n[i];
temp2 = temp;
}
}
return mode;
}
-Just use a HashMap which contains the array index values as the keys and their occurrence numbers as the values.
-Update the HashMap as you traverse the for loop by checking to see if the current index already exists in the HashMap. IF IT DOES then find that double in the hash map and see how many times it has already occurred and put it back in the HashMap with one more occurrence.
-I did it in Java because that's what it looks like you are using. What's also good is that the time complexity is O(n) which is the best you could possibly get for this type of scenario because you have to visit every element at least once.
-So if you have an array like this of doubles: { 1,2,3,1,1,1,5,5,5,7,7,7,7,7,7,7,7,7}
Then the hash map will look something like this at the end: { 1->4, 2->1, 3->1, 5->3, 7->9 }
Meaning that "1 occurred 4 times, 2 occured 1 time .... 7 occurred 9 times" etc.
public static double mode(double [] arr)
{
HashMap arrayVals = new HashMap();
int maxOccurences = 1;
double mode = arr[0];
for(int i = 0; i<arr.length; i++)
{
double currentIndexVal = arr[i];
if(arrayVals.containsKey(currentIndexVal)){
int currentOccurencesNum = (Integer) arrayVals.get(currentIndexVal);
currentOccurencesNum++;
arrayVals.put(currentIndexVal, currentOccurencesNum );
if(currentOccurencesNum >= maxOccurences)
{
mode = currentIndexVal;
maxOccurences = currentOccurencesNum;
}
}
else{
arrayVals.put(arr[i], 1);
}
}
return mode;
}
This code is a different way that does not use hashmaps. This method, created in java, takes an array as the parameter and creates another array called "numberCount" within the method. This array "numberCount" will set its index to the value in the array. The index of "numberCount"that contains the value in the array passed will add 1 to the value of "numberCount" ("++numberCount[array[i]]") then will go to the next value in the array (repeat until the end of the array). Then creates another for loop to go through each value of the array in "numberCount", which ever index has the highest value/count will be stored and return as "max." This method will have to undergo some difficult changes to use a double array. but seems to work great with an int array.
public static int findMostFrequentValue(int[] array) {
int i;
int[] numberCount = new int[100];
for (i = 0; i < array.length; i++)++numberCount[array[i]];
int max = 0;
int j;
for (j = 0; j < numberCount.length; j++) {
if (numberCount[j] > max) max = j;
}
return max;
}
You should check the number of occurances of every element in your array. You can do it by comparing every element of array with herself and others via 2 inner for loops.
Remember, if the array is not sorted and contains more then 1 modal value (thus repeating number of occurances) this will return the first one. It maybe wise to order the array first by Arrays.sort(array) so that you can pick the smallest or biggest modal value.
public static int modeOfArray(int[] array){
int mode;
int maxOccurance = 0;
for(int i=0; i<array.length; i++){
int occuranceOfThisValue = 0;
for(int j=0; j<array.length; j++){
if(array[i] == array[j])
occuranceOfThisValue++;
}
if(occuranceOfThisValue > maxOccurance){
maxOccurance = occuranceOfThisValue;
mode = array[i];
}
}
return mode;
}

Categories

Resources