Delete duplicates in array, Java [duplicate] - java

This question already has answers here:
How to efficiently remove duplicates from an array without using Set
(48 answers)
Closed 8 years ago.
I have written a method to count the number of occurrences of the words in a word file. Prior, in another method, i have sorted the words to appear in alphabetical order. There for a sample input into this method will look like this:
are
away
birds
birds
going
going
has
My question is.. How do i delete the repeated occurrences in this method? (after counting ofcoz) I have tried to use another string array to copy the unique ones into that string array, but i get a null pointer exception.
public static String[] counter(String[] wordList)
{
for (int i = 0; i < wordList.length; i++)
{
int count = 1;
for(int j = 0; j < wordList.length; j++)
{
if(i != j) //to avoid comparing itself
{
if (wordList[i].compareTo(wordList[j]) == 0)
{
count++;
}
}
}
System.out.println (wordList[i] + " " + count);
}
return wordList;
}
Any help will be much appreciated.
Oh, and my current output looks something like this:
are 1
away 1
birds 2
birds 2
going 2
going 2
has 1

I would prefer using Map to store word occurrence. Keys in the map are stored in Set so it can't be duplicated. What about something like this?
public static String[] counter(String[] wordList) {
Map<String, Integer> map = new HashMap<>();
for (int i = 0; i < wordList.length; i++) {
String word = wordList[i];
if (map.keySet().contains(word)) {
map.put(word, map.get(word) + 1);
} else {
map.put(word, 1);
}
}
for (String word : map.keySet()) {
System.out.println(word + " " + map.get(word));
}
return wordList;
}

I already posted an answer on this question. Your question is almost identical - he was having problems creating another array and getting an NPE too.
This is what I came up with (assuming the array is sorted):
public static String[] noDups(String[] 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].equals(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)
String[] returnArray = new String[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].equals(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
}
Sample input/output:
String[] array = {"are", "away", "birds", "birds", "going", "going", "has"};
array = noDups(array);
// print the array out
for (String s : array) {
System.out.println(s);
}
Outputs:
are
away
birds
going
has

Related

can not determinate index in array

Strings are added to the array, to determine whether the list is ordered by increasing the length of the string. If not, print the index of the first element that violates such ordering.
Everything works correctly if the strings in the array are different, for example, enter
113
13476
Neutral
wa
Answer: index (wa) 3 output.
but if it will be like this:
123
12345
123
Answer: index (123) - 0 but the correct answer is index 2
public class Solution {
public static void main(String[] args) throws IOException {
Scanner scan = new Scanner(System.in);
ArrayList<String> list = new ArrayList<>();
for (int i = 0; i < 4; i++) {
list.add(scan.nextLine());
}
int count = 0;
for(int i = 0; i < list.size(); i++){
if(count+2 > list.size()) {
break;
}
if(list.get(i+1).length() <= list.get(i).length()){
System.out.println(list.indexOf(list.get(i+1)));
break;
}
count = count + 1;
}
}
}
You should change
list.indexOf(list.get(i+1))
to
i+1
since if there are multiple occurrences of the same String in the List, you want to return the index of the first element that violates the ordering, which is i+1 (and not the index of the first String which is equal to that element).
BTW, even if there were no duplicate elements in your List, it would no sense to use list.indexOf(list.get(i+1)) instead of simply i+1.
You don't need to use lastIndexOf - you already have the index:
// Stsrt at index 1, as index 0 can never violate the rule:
for (int i = 1; i < list.size(); i++) {
if (list.get(i).length() < list.get(i - 1).length() {
System.out.println("Rule violated at index " + i + " (" + list.get(i) + ")");
break;
}
}
You could also use PriorityQueue and check within the supplied Comparator
PriorityQueue<String> p = new PriorityQueue<>((a, b) -> {
if (a.length() > b.length()) {
throw new RuntimeException(a);
}
return 0;
});
p.add("foo");
try {
p.add("bar2");
} catch (RuntimeException e) {
System.out.println(p.size());
}
}

Java: Print out each number in an array without printing its an repeats of that number?

Im trying to print out an array but only print out the distinct numbers in that array.
For example: if the array has {5,5,3,6,3,5,2,1}
then it would print {5,3,6,2,1}
each time i do it either i only print the non repeating numbers, in this example {6,2,1} or i print them all. then i didnt it the way the assignment suggested
the assignment wants me to check the array before i place a value into it to see if its there first. If not then add it but if so dont.
now i just keep getting out of bounds error or it just prints everything.
any ideas on what i should do
import java.util.Scanner;
public class DistinctNums {
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
int value;
int count = 0;
int[] distinct = new int[6];
System.out.println("Enter Six Random Numbers: ");
for (int i = 0; i < 6; i++)
{
value = input.nextInt(); //places users input into a variable
for (int j = 0; i < distinct.length; j++) {
if (value != distinct[j]) //check to see if its in the array by making sure its not equal to anything in the array
{
distinct[count] = value; // if its not equal then place it in array
count++; // increase counter for the array
}
}
}
// Displays the number of distinct numbers and the
// distinct numbers separated by exactly one space
System.out.println("The number of distinct numbers is " + count);
System.out.print("The distinct numbers are");
for (int i = 0; i < distinct.length; i++)
{
System.out.println(distinct[i] + " ");
}
System.out.println("\n");
}
}
Always remember - if you want a single copy of elements then you need to use set.
Set is a collection of distinct objects.
In Java, you have something called HashSet. And if you want the order to be maintained then use LinkedHashSet.
int [] intputArray = {5,5,3,6,3,5,2,1};
LinkedHashSet<Integer> set = new LinkedHashSet<Integer>();
//add all the elements into set
for(int number:intputArray) {
set.add(number);
}
for(int element:set) {
System.out.print(element+" ");
}
You can make this using help array with lenght of 10 if the order is not important.
int [] intputArray = {5,5,3,6,3,5,2,1};
int [] helpArray = new int[10];
for(int i = 0; i < intputArray.length ; i++){
helpArray[intputArray[i]]++;
}
for(int i = 0; i < helpArray.length ; i++){
if(helpArray[i] > 0){
System.out.print(i + " ");
}
}

Iterating through ArrayList to get 5 Largest Numbers

Yes, this is homework, but I need some help with it. I have been able to make it sort through the highest number, but none of the numbers are correct after that. List of numbers: http://pastebin.com/Ss1WFGv1
Right now, we are learning arrays, so is this simply trying to shoot a fly with a cannonball?
package hw2;
import java.io.BufferedReader;
import java.io.FileReader;
import java.util.ArrayList;
public class HW2 {
public static ArrayList<Integer> nums1 = new ArrayList<Integer>();
public static int size = 0;
public static void main(String[] args) throws Exception {
ArrayList<Integer> sortedNums = new ArrayList<Integer>();
readFile();
System.out.println("Name: Jay Bhagat" + "\n" + "Email: xxxxxx");
size = nums1.size();
for(int l = 0; l<=10;l++){
nums1.set(sortThis(nums1, l), 90009);
System.out.println("\n\n");
}
// for (int k = 0; k <= size - 1; k++) {
// System.out.println("Number " + (k + 1) + sortedNums.get(k));
//
// }
}
public static void readFile() throws Exception {
BufferedReader reader = new BufferedReader(new FileReader("L:\\numbers.txt"));
while (reader.readLine() != null) {
nums1.add(Integer.parseInt((reader.readLine())));
}
reader.close();
}
public static int sortThis(ArrayList<Integer> current, int offset) {
int j = 0;
int tempNum = 0;
int curNum = 0;
int finalIndex = 0;
int prevIndex = 0;
int curIndex = 0;
for (j = 0; j < size-offset; j++) {
curIndex = j;
nums1.trimToSize();
curNum = current.get(j);
//Thread.sleep(1000);
if(curNum!=90009){
if (curNum > tempNum) {
tempNum = curNum;
System.out.println(tempNum);
prevIndex = j;
finalIndex = prevIndex;
}
if (curNum < tempNum) {
finalIndex = prevIndex;
}
}
}
return finalIndex;
}
}
An approach that lets you make just one pass through the list and doesn't require sorting:
Declare an array of 5 integers: int[] largest = new int[5];
Put the first 5 elements in the ArrayList into largest.
Starting with the 6th element, look at each element N in the ArrayList, and if N is larger than any element in largest, throw out the smallest number currently in largest and replace it with N.
If you need to exclude duplicates, the algorithm can be modified easily (just skip over any ArrayList element that's already in largest).
Why not use Collections.sort(List list) or Arrays.Sort(arr). This will save much of effort. Or is it part of your task?
Assuming your collection is sorted, and you want the last 5 elements, try this out:
for (int i = sortedNums.size() - 5; i < sortedNums.size(); ++i) {
System.err.println(sortedNums.get(i));
}
How I would go about doing this:
Create a temporary ArrayList, as a copy of the initial one.
After each largest element is found, remove it from the temporary ArrayList and add it to your 5 largest numbers
Repeat until complete
edit* This does not require your elements to be sorted, and has a fairly poor efficiency as a result
I assume you do not have the liberty to use sort and suchlike, considering this is a homework. So here is outline of an algorithm that you can try to implement
create an array of five integers (we will keep this sorted)
for each element in the list
find the index of the element in the array that it is greater than
if no such element exists in the array (i.e. it is smaller than all elements in the array)
continue on to the next element in the list
else
push all elements in the array to one index below, letting them fall off the
edge if need be (e.g. if the number in list is 42 and the array has
45 and 40 at index 3 and 2 respectively then
move arr[1] to arr[0], and arr[2] (40) to arr[1] and set arr[2] = 42)
end if
end for
At the end the array will have the five elements
I will leave one question for you to answer (it is important): what should you set the array to initially?
You only need two lines of code:
Collections.sort(nums1);
List<Integer> high5 = nums1.subList(nums1.size() - 5, nums1.size());
If you must "do it yourself", the simplest way to sort is a bubble sort:
iterate over the list
swap adjacent numbers if they are in the wrong order
repeat n times
Not efficient but very easy to code.

How to put strings into a matrix?

I'm having trouble with this, maybe you could help me:
I have 3 strings like: word1, word2, word3 and I have to build a matrix with them, like this:
on the first row : word1("ABC"), second row: word2("DEF") and third row: word3("GHI").
A|B|C
D|E|F
G|H|I
I need this because after that I have to check if the formed words ("ADG","BEH","CFI") are in an array of words. And I don't know how to put those strings in the matrix so I can check. Any help is useful.
Thanks
Based on this comment:
the words have the same size, because the matrix is actually like a puzzle. I choose randomly 3 words from an array, put them in a matrix and check after that if the words resulted are from the same array.
I'll assume some things in order to make this work (since we don't have enough info):
You have an array of Strings where you have all the words
private String[] words;
You have a method to randomly pick up 3 Strings from this array.
private String s1, s2, s3;
public void pickThreeRandomWords() {
s1 = aRandomWord(words);
s2 = aRandomWord(words);
s3 = aRandomWord(words);
//or maybe another fancy algorithm to get this...
}
So you would need an array of array of chars based on these 3 Strings. This code could do the work for you:
public char[][] createMatrixFromStrings(String s1, String s2, String s3) {
char[][] theMatrix = new char[3][]; //yes, hardcoded
theMatrix[0] = s1.toCharArray();
theMatrix[1] = s2.toCharArray();
theMatrix[2] = s3.toCharArray();
return theMatrix;
}
Of course, if you would want to make this method to support more than 3 Strings you can make the method to receive a random quantity of Strings:
public char[][] createMatrixFromStrings(String ... strings) {
if (strings == null || strings.length == 0) return null;
char[][] theMatrix = new char[strings.length][];
int i = 0;
for(String s : strings) {
theMatrix[i++] = s.toCharArray();
}
return theMatrix;
}
You can build the result words without a matrix:
List<String> verticalWords = new ArrayList<String>();
for (int i = 0; i < horizontalLen; i++){
String currentWord = "";
for (int j = 0; j < wordCount; j++)
currentWord += words.get(j).get(i);
verticalWords.add(currentWord);
}
P.S. For the currentWord you can use a StringBuilder to make it more efficient, but I doubt it is highly needed here.
Java doesn't have matrix.It has array of array
So,you can try this
List<char[]> lst=new ArrayList();//stores a list of char[]
lst.add(("ADC".toCharArray()));//adds array of characters i.e 'A','D','C'
lst.add(("DEF".toCharArray()));
lst.get(0)[0];//A
lst.get(1)[0];//D
Now you can iterate vertically
for(int i=0;i<lst.size();i++)temp+=lst.get(i)[0];
temp would have AD which you can now cross check with equals method
The main thrust of this goal is that you're taking a one-dimensional value, and converting it into a two-dimensional value. There are many ways you can do this, but here are the two that come off the top of my head:
Set up a nested while loop to iterate over the first dimension, and when it reaches the length, reset and cause the outer loop to increment, much like a clock
You can create a new subarray using ArrayUtils.toSubArray(), and with some finagling, get that to work:
Create a new row of the array each time, based on the dimension slices you want to hit up. I'll leave figuring this one out as an exercise for the reader. But here's a hint:
for(int i = 0; i < theDimension; i++, j += 3) {
ret[i] = ArrayUtils.subarray(word, i*theDimension, j);
}
Lastly, I assume that there's a restraint on the type of input you can receive. The matrix must be square, so I enforce that restriction before we build the array.
I strongly encourage you to poke and prod this answer, and not just blindly copy it into your schoolwork. Understand what it's doing so you can reproduce it when you're asked to again in the future.
public char[][] toMatrix(int theDimension, String theEntireWord) {
if(theEntireWord.length() != theDimension * theDimension) {
throw new IllegalArgumentException("impossible to add string to matrix of uneven dimension");
}
char[][] ret = new char[theDimension][theDimension];
int i = 0;
int j = 0;
while(i < theDimension) {
if(j == theDimension) {
j = 0;
++i;
} else {
ret[i][j] = theEntireWord.charAt((i * theDimension) + j);
j++;
}
}
return ret;
}
I think this will sort your problem.
package printing;
public class Matrix {
public static void main(String[] args) {
//Length can define as you wish
String[] max = new String[10];
String[] out = null;
//Your Inputs
max[0]="ADG";
max[1]="BEH";
max[2]="CFI";
//following for loop iterate your inputs
for (int i = 0; i < max.length; i++) {
if(out==null){out= new String[max.length];}
String string = max[i];
if(string==null){ break;}
//Here breaking input(words) one by one into letters for later contcatnating.
String[] row = string.split("");
for (int j = 0; j < row.length; j++) {
String string1 = row[j];
// System.out.println(string1);
//create the values for rows
if(out[j]!=null){ out[j]=out[j]+string1;}
else{
out[j]=string1;
}
}
}
//following for loop will out put your matrix.
for (int i = 0; i < out.length; i++) {
String string = out[i];
if(out[i]==null){break;}
System.out.println(out[i]);
}
}
}

Java duplicates distinct unique array value

I am trying to solve this, but i don't know how...
Values[10] = {1,1,4,4,2,3,3,2,1,3}
to print:
{1,2,3,4} or {1,4,2,3} (not sorted, any order, but distinct)
I also need to count the number of times each number has occurred, both without sort, new arrays or boolean methods or other data structures, please advise as i am stuck.
Is there a simple method i can use to just print the unique values/ distinct values ?
It can be accomplished if your are willing to destroy your current array. and you assume that the array is either of type Integer (so nullable) or if not there is some bound such as all int are poistive so you can use -1.
for(int i = 0; i < values.length; i++){ //for entire array
Integer currVal = values[i]; // select current value
int count = 1; // and set count to 1
if(currVal != null){ // if value not seen
for( int j = i + 1; j < values.length; j++){ // for rest of array
if(values[j] == currVal){ // if same as current Value
values[j] = null; // mark as seen
count++; // and count it
}
}
System.out.print("Number : " + currVal + " Count : " + count + "\n");
//print information
}
// if seen skip.
}
In plain english, Go through the array in 2 loops, roughly O(n^2) time.
Go to index i. If index has not yet been seen (is not null) then go through the rest of array, mark any indexs with same value as seen (make it null) and increment count varable. At end of loop print value and count. If Index has be seen (is null) skip and go to next index. At end of both loops all values will be left null.
Input : Values[] = {1,1,4,4,2,3,3,2,1,3}
Output : Values[] = {1,null,4,null,2,3,null,null,null,null}
Number : 1 Count : 3
Number : 4 Count : 2
Number : 2 Count : 2
Number : 3 Count : 3
Edit: corrected my mistake in output, pointed out by commenters.
Another solution, without creating additional objects:
Arrays.sort(values);
for(int i = 0; i < values.length; i++) {
if (i == 0 || value[i] != value[i-1]) {
System.out.println(values[i]);
}
}
And the shortest solution I can think of:
Integer[] values = {1,1,4,4,2,3,3,2,1,3};
Set<Integer> set = new HashSet<Integer>();
set.addAll(Arrays.asList(values));
System.out.println(set);
Assuming the values are guaranteed to be integers, you could also do it by incrementing a check value, scan over the array, sum the number of that check value in the array, add it to an accumulator and loop while the accumulator < array.length.
Something like this (untested):
public void checkArray(int[] toCheck) {
int currentNum = 0;
int currentCount = 0;
int totalSeen = 0;
StringBuilder sb = new StringBuilder();
int min = Integer.MAX_VALUE;
int max = Integer.MIN_VALUE;
for(int i=0; i<toCheck.length; i++) {
min = Math.min(toCheck[i], min);
max = Math.max(toCheck[i], max);
}
System.out.print("{ ");
for(currentNum = min; currentNum < max; currentNum++) {
for(int i=0; i<toCheck.length; i++) {
if(toCheck[i] == currentNum) currentCount++;
}
if(currentCount != 0) {
if(currentNum == min) System.out.print(currentCount + "(" +currentCount+ ")");
else System.out.print(", " + currentCount + " (" +currentCount+ ")");
}
totalSeen += currentCount;
currentCount = 0;
}
System.out.println(" }");
}
It should be noted that while this technically fulfills all your requirements, it will be far less efficient than gbtimmon's approach.
If your ints were {1,2,3,150000}, for example, it will needlessly spin over all the values between 4 and 149999.
Edit: added better limits from tbitof's suggestion.
Your question isn't quite clear to me, since it sounds like you want to do these things without creating any additional objects at all. But if it's just about not creating another array, you could use a Map<Integer, Integer>, where the key is the number from your original array, and the value is the count of times you've seen it. Then at the end you can look up the count for all numbers, and print out all the keys by using Map.keyset()
Edit: For example:
Map<Integer,Integer> counts = new HashMap<Integer, Integer>();
for( int i : values ) {
if( counts.containsKey(i) ) {
counts.put(i, counts.get(i) + 1);
} else {
counts.put(i, 1);
}
}
// get the set of unique keys
Set uniqueInts = counts.keyset();

Categories