Removing duplicate characters in a String array - java

I have a sample input like [q w e r r t] and I want to remove duplicates and print [q w e r t] with arrays. I don't see why the output is different for the below code snippet.
for(int j=0; j< array.length; j++) {
for(int k=j+1; k< array.length; k++) {
if(array[j] == array[k]) {
continue;
}
System.out.print(array[j] + " ");
j = k;
}
}
Update: I wanted to use this logic for a sorted array. I used Arrays.sort(). I changed == to .equals() for Strings.
public static void main(String args[]) throws IOException {
// Enter size of array and assert the type of input
System.out.println("Enter size of array in integers");
Scanner sc = new Scanner(System.in);
while (!sc.hasNextInt()) {
System.out.println("Please enter integers");
sc.next();
}
;
// Accepting the values into the array and sorting them
int demoInt = sc.nextInt();
String[] array = new String[demoInt];
String[] outputMarkers = new String[demoInt];
System.out.println("Enter the values");
for (int i = 0; i < array.length; i++) {
Scanner scNum = new Scanner(System.in);
array[i] = scNum.next();
if (i == array.length - 1) System.out.println("Array is full");
}
Arrays.sort(array);
System.out.printf("Sorted array is : %s", Arrays.toString(array));
//Checking for duplicates //Sample: a a a s d f
for (int j = 0; j < array.length; j++) {
for (int k = j + 1; k < array.length; k++) {
if (array[j].equals(array[k])) {
continue; //returns to for loop with increment
}
System.out.print(array[j] + ". ");
j = k;
}
}
}
Input: a a a d f
Output: a d f

Your problem is that you are checking each character against all the characters after it. Imagine an array with no duplicates; once you get to the last character, you have printed out all the characters before it. But when j = array.length - 1, then k = array.length, and the second for loop does not run at all, and your last character will never be printed.
Your code would always fail to print the last element correctly. The only case in which it would be correct is if your last element is a duplicate of a previous element, but not of the second-to-last element.
Try this code instead:
outerloop:
for (int j = 0; j < array.length; j++) {
for(int k = 0; k < j; k++) {
if(array[j] == array[k]) {
continue outerloop;
}
}
System.out.print(array[j] + " ");
}
The premise of the code is that it loops through each of the characters. If it matches any of the previous characters, the code skips that element and continues to the next one.
EDIT: Looks like you edited the question for a sorted array instead. That means if the last element is a duplicate, it will be a duplicate of the element before it so we don't have to worry about the corner case in my previous block of code.
for(int j=0; j< array.length; j++) {
for(int k=j+1; k< array.length; k++) {
if(array[j] == array[k]) {
continue;
}
System.out.print(array[j] + " ");
j = k;
}
}
System.out.print(array[array.length-1] + " ");

If you are looking to remove the values rather than just skip over them when printing, you will want to start from the end of your array and work towards 0, calling array.remove(i) when you find an object that matches a previously checked object.
Though that is just to do it as a loop exercise. It would be easier to push your array into a Set.

You can use a Boolean array of size 122, make all the values in the array as false, iterate the give character array, if the ASCII value of character is false, thena make it true and print it.
Below is the example code, here I have taken a string and removing all the duplicates and printing the resulting string:
static String removeDuplicate(String s) {
boolean[] flagArr = new boolean[122];
int sLength = s.length();
StringBuilder resultStr = new StringBuilder();
for (int i = 0; i < sLength; i++) {
char tempChar = s.charAt(i);
int tempVal = (int) tempChar;
if (!flagArr[tempVal]) {
flagArr[tempVal] = true;
resultStr.append(tempChar);
}
}
return resultStr.toString();
}
The complete code is at
Removing Duplicate Characters From String Without Using Set | jain Tarun Blog

Why not use only one loop ?
//assuming array has length >= 2
System.out.print(array[0] + " ");
for(int j=1; j< array.length; j++) {
if(array[j] == array[j - 1]) {
continue;
}
System.out.print(array[j] + " ");
}

Related

Below is my Java program for finding duplicate. Here the output is repeated I want only duplicate character as output

public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
String s1 = sc.nextLine();
int count = 0;
// breaking in to characters
char[] str1 = s1.toCharArray();
System.out.println("Duplicate are :");
//creating outer loop for string length
for (int i = 0; i < s1.length(); i++) {
//creating inner loop for comparison
for (int j = i + 1; j < s1.length(); j++) {
//comparing value of i and j
if (str1[i] == str1[j]) {
System.out.println(str1[j]);
System.out.println(count);
//increment after comparison
count++;
break;
}
}
}
sc.close();
}
OUTPUT:
aassdesdd
Duplicate are :
a
s
s
d
d
If you only want to print consecutive duplicates (i.e. for the input "aassdesdd", output asd and not assdd), you can combine the inner loop with the equality check:
for(int i = 0; i < s1.length(); i++) {
for(int j = i + 1; j < s1.length() && str1[i] == str1[j]; j++) {
System.out.println(str1[j]);
}
}
If you just wanted to print consecutive distinct character, then you have only one loop, and each iteration, you can just check current and next character. If they are same, then print. To avoid same character printed again, we can have flag. This can be achieved using single loop
char[] str1 = "aasssdesdd".toCharArray();
boolean flag=true;
for(int i = 0; i < str1.length-1; i++) {
if (flag && str1[i]==str1[i+1])
{
System.out.println(str1[i]);
// we found duplicate, mark the flag as false
flag=false;
continue;
}
flag = true;
}
Output :
a
s
d
Demo

line 21 show ; expected

The first line contains a single integer p denoting the length of array. The second line contains space-separated integers describing each respective element in array. The third line prints an integer indicating the number of negative arrays.
package asgn3;
import java.util.*;
public class Asgn3 {
public static void main(String[] args) {
int count = 0, result = 0;
Scanner in = new Scanner(System.in);
System.out.println("Enter the array ");
String s = in.nextLine();
int j = 0;
String[] s1 = s.split(" ");
int a[] = new int[s1.length];
for(String s2:s1) {
a[j] = Integer.parseInt(s2));
j++;
}
for (int i = 0; i < a.length; i++) {
for ( j = i; j < a.length; j ++) {
for (int k = i; k <= j; k++) {
result += a[k];
}
if(result < 0)
count ++;
}
System.out.println("no. of negatve arrays is "+count);
}
}
}
The issues is usage of extra unnecessary parenthesis. Change,
a[j]=Integer.parseInt(s2));
with
a[j]=Integer.parseInt(s2);
Remove extra bracket ) from end of line
a[j] = Integer.parseInt(s2);

Nested for loops 0123

I need to create a nested for loops that gives the following output,
0
1
2
3
This is what I have, but for the second test, userNum is replaced by 6 and obviously my code fails.. help?
public class NestedLoop {
public static void main (String [] args) {
int userNum = 0;
int i = 0;
int j = 0;
for(i = 0; i <= userNum; i++){
System.out.println(i);
for(i = 1; i <= userNum; i++){
System.out.println(" " +i);
for(i = 2; i <= userNum; i++){
System.out.println(" " +i);
for(i = 3; i <= userNum; i++){
System.out.println(" " + i);
}
}
}
}
return;
}
}
I think (it's a guess, though) that you're looking for this.
public static void main (String [] args)
{
int limit = 6;
for(int i = 0; i <= limit; i++)
{
for(int j = 0; j < i; j++)
System.out.print(" ");
System.out.println(i);
}
}
The reason why your approach fails is, as I see it, that you are looping through the numbers to show (which is right) but you fail to loop up on the number of spaces (which I resolved by relating the inner loop's limit to the outer loop's current value.
Let's talk a bit about what your intention is with these loops.
The inner loop is meant to produce an arbitrary number of spaces, depending on what number you're iterating on. So if you're on number 0, you produce no spaces, and if you're on 1, you produce one space, and so forth. The other caveat is that they all must appear on the same line, so System.out.println is the incorrect choice.
You would want to use System.out.print to print out the spaces. So let's write that.
for(int j = 0; j < 6; j++) {
System.out.print(" ");
}
This will print out six spaces unconditionally. What that condition is depends on the current number we're iterating on. That comes from your outer loop.
You only need to define a loop that starts from an arbitrary starting point - like 0 - and then loop until you are at most your ending number. For this, your current loop is sufficient:
for(i = 0; i <= userNum; i++) {
}
Now, we need to bring the two pieces together. I leave the figuring out of the question mark and what to print after you've printed the spaces as an exercise to the user, bearing in mind that you must stop printing spaces after you've reached your number.
for(int i = 0; i <= userNum; i++) {
for(int j = 0; j < ?; j++) {
System.out.print(" ");
}
}
Let's analyse the task
In every line, we should print a number and different number spaces in the front of the number.
For that, we need two loops - one outer to iterate from 0 to N and one inner to add spaces in front of the number.
private static void method1(int userNum) {
int nummSpaces = 0;
for (int i = 0; i <= userNum; i++) {
for (int j = 0; j < nummSpaces; j++) {
System.out.print(" ");
}
nummSpaces++;
System.out.println(i);
}
}
In this solution, we have variable numSpaces which used to count the number of spaces in front of the number. It is unneeded - we can use variable i for that purpose.
private static void method2(int userNum) {
for (int i = 0; i <= userNum; i++) {
for (int j = 0; j < i; j++) {
System.out.print(" ");
}
System.out.println(i);
}
}
Let's analyses once again the output
- the fist line: printed zero spaces and number 0
- the second line: printed one space and number 1
- the third line: printed two spaces and number 2
- and so on
Finally, we can use just one variable, which contains spaces and after that print the length of it:
private static void method3(int userNum) {
for (String spaces = ""; spaces.length() <= userNum; spaces += " ") {
System.out.println(spaces + spaces.length());
}
}
C/C++
#include <iostream>
using namespace std;
int main() {
int userNum;
int i;
int j;
cin >> userNum;
for (i = 0; i <= userNum; ++i) {
for (j = 0; j < i; ++j) {
cout << " ";
}
cout << i << endl;
}
return 0;
}

How to count 1st duplicates value in array in Java

I have taken array int[] a = {33,33,5,5,9,8,9,9}; In this array so many values are duplicates means 33 comes twice & 5 also comes twice & 9 comes three times.
But I want to count the first value which is duplicate means 33 is first value which comes twice so answer would be 2.
I try:
public class FindFirstDuplicate
{
public static void main(String[] args) {
int c=0;
int[] a = {33,33,5,5,9,8,9,9};
outerloop:
for(int i = 0; i < a.length; i++)
{
for(int j = i+1; j< a.length; j++)
{
if(a[i] == a[j])
{
System.out.println(a[i]); //Duplicate value
c++;
break outerloop;
}
}
}
System.out.print("Count: "+c);
}
}
Output:
33
1
public class HelloWorld{
public static void main(String[] args) {
int[] a = {33,33,5,5,9,8,9,9};
for(int i = 0; i < a.length; i++)
{
int c=1; // we already found one.
// and we initialize this counter inside the loop,
// so that it is reset for each new starting number.
for(int j = i+1; j< a.length; j++) // we're starting from next number (reason we start with c=1)
{
if(a[i] == a[j])
c++;
}
if(c > 0) {
System.out.println("First uplicate value: "+ a[i] + " Count: " + c);
break; // we have to break out of the outer loop,
// so the inner loop can finish counting duplicates
}
}
}
}
Try something like:
int[] numbers = {33, 33, 5, 5, 9, 8, 9, 9};
Set<Integer> set = new HashSet<Integer>();
for (int i = 0; i< numbers.length; i++) {
if (!set.add(number[i])) {
System.out.println("first duplicate is " + number[i] + " and index is " + i);
break;
}
}
If the values in the array are non-negative and reasonably small, you can use a BitSet to store whether or not you have seen a value previously:
BitSet bits = new BitSet();
for (int i = 0; i < numbers.length; ++i) {
if (bits.get(numbers[i])) {
System.out.println("first duplicate at " + i + ": " + numbers[i]);
break;
}
bits.set(numbers[i]);
}
You could try this out:
int[] a = {33,33,5,5,9,8,9,9};
Integer[] uniques = new Integer[a.length];
Integer[] counts = new Integer[a.length];
int len = 0;
for(int num : a){
boolean matched = false;
for(int i = 0; i < len; i++){
if(num == uniques[i].intValue()){
matched = true;
counts[i] = new Integer(counts[i]+1);
break;
}
}
if(!matched){
uniques[len] = new Integer(num);
counts[i] = new Integer(1);
len++;
}
}
for(int i = 0; i < len; i++){
if(counts[i].intValue() > 1){
System.out.println("first duplicate is " + uniques[i] + " and number of times it appears " + counts[i]);
break;
}
}
In your code you exit both loops after the first duplicate is found, so any other occurences of the element would be ignored.
Also you start with c = 0. When you get to the second occurence, c will be incremented and be 1, not 2.
To count all elements simply change the loop condition of the outer loop and remove the break:
int c = 1;
int i;
for(i = 0; (c == 1) && (i < a.length); i++)
{
for(int j = i+1; j < a.length; j++)
{
if(a[i] == a[j])
{
c++;
}
}
}
System.out.println(a[i]); //Duplicate value
System.out.print("Count: "+c); // maybe do something else, if c == 1 (no duplicates)???
However SMA's answer describes a more performant way (for arbitrary input arrays) of finding the first duplicate. Once you found the second occurence of the first duplicate, you'd only need to count the number of occurences in the rest of the array to get the final count.

If statements in 2D arrays

When I am trying to run this code it shows java.lang.ArrayIndexOutOfBoundsException Error. Please help me to fix this code.
import java.util.*;
class Example {
public static void main(String args[]) {
Scanner input = new Scanner(System.in);
Random r = new Random();
final int N, S;
System.out.print("Input No of Students : ");
N = input.nextInt();
System.out.print("No of Subject : ");
S = input.nextInt();
int[][] st = new int[N][S];
int[] stNo = new int[N];
int[] stMax = new int[N];
for (int i = 0; i < N; i++) {
stNo[i] = r.nextInt(10000);
for (int j = 0; j < S; j++) {
st[i][j] = r.nextInt(101);
}
}
// Find max Value of marks of a Student
for (int i = 0; i < N; i++) {
for (int j = 0; j < S; j++) {
if (st[i][j] > st[i][j + 1]) {
stMax[i] = st[i][j + 1];
}
}
}
// Display marks
// Dispaly Column names
System.out.print("stNo\t");
for (int i = 1; i < S + 1; i++) {
System.out.print("Sub " + i + "\t");
}
System.out.print("Max");
// Print Values
for (int i = 0; i < N; i++) {
System.out.print(stNo[i] + "\t");
for (int j = 0; j < S; j++) {
System.out.print(st[i][j] + "\t");
}
System.out.print(stMax[i]);
System.out.println();
}
}
}
The error is
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: (here shows the input for "S")
at pack1.Example.main(Example.java:31)
As I am a new to coding I can not fix this. Please help me to fix this.
Thanks
An ArrayIndexOutOfBoundsException error means you exceed the boundaries of the array. In your case, st has S colomns and you tried to reach the S+1-th element (index S).
st[i][j + 1] => when j == S-1 (the end of the loop), you do an out of bounds.
Now, as your comment say, you're looking for the max value. Then the code should be:
stMax[i] = 0;
for (int j = 0; j < S; j++) {
if (st[i][j] > stMax[i]) {
stMax[i] = st[i][j];
}
}
What your code is doing is comparing the current value to the next one. And every time the next value is greater than the current one, you update stMax[i]. This does not make sense.
This line is causing the exception:
stMax[i] = st[i][j + 1];
You are iterating j to the end of the array, and always looking for the next element. So when j reaches the end of the array it is still looking for one more index, hence the outOfBoundsException.

Categories