Good day everyone.
I'm not quite sure on how to check for the same elements in an array example.
%java stuff 4 6 1 2 3 1
/* Now that there are two ones in the array it should pump out "Yes! The same!"*/
I do realize however that I can take the first value in the array and check that with a for loop and then so on and so forth.
I'm just not quite confident on the syntax yet.
So far I've tried putting up an if case for checking it put it doesn't work. Can anyone please be so kind and help me understand my project a little bit better?
P.s. I'm open towards all improvements of this question.
public class seeIT
{
public static void main (String[] args)
{
int N = args.length;
int [] a = new int[N];
boolean flag = false;
for ( int i = 0; i < N; i++)
{
a[i] = Integer.parseInt(args[0]);
}
for(int i = 0; i < N; i++)
for(int j = i +1; j < N; j++)
{ if(a[i] == a[j])
{ flag = true;
} else
{
System.out.print("correct, there are no numbers that are the same here");}
}
}
}
I created the boolean flag because, again, I realize that I need to check whether or not the statement is true or not.
Thank you all for kind answers and have a nice day.
Josef.
Add the elements to the set (HashSet), If the set.add returns false on the element, which means that element is repeated.
HashSet would be the class to use for this kind of problem, however it doesn't hurt to do it "manually" if you're learning. Here are some comments on your code:
a[i] = Integer.parseInt(args[0]);
I assume you meant
a[i] = Integer.parseInt(args[i]);
otherwise you would be putting args[0] at every position in a.
if(a[i] == a[j]) {
flag = true;
} else {
System.out.print("correct, there are no numbers that are the same here");
}
You are printing the result too soon - before you can know it. At this point you just know whether two particular elements are the same (and you correctly set the flag if they are), but you have to wait until the loops finish to know that there were no such elements in the whole array.
First of all, I would suggest using a HashSet since it would take care of all repetition checking for you. But since you are in a learning stage, I will rather stick with your approach here.
I suggest putting your array checking logic in a separate method that returns a boolean. This way, you can return true as soon as you find a repeated number (return immediately exits a method), thereby avoiding uselessly iterating over the rest of the array. This also makes your code reusable.
This gives the following code. I also did some reformatting to make the code more readable, and I corrected a typo that makes your code repeatedly add the first argument into the int array.
public class SeeIT {
public static void main(String[] args) {
int n = args.length;
int[] a = new int[n];
boolean flag = false;
for (int i = 0; i < n; i++) {
a[i] = Integer.parseInt(args[i]);
}
boolean repeats = hasRepetitions(a);
if (repeats) {
System.out.println("There is at least one repeated number.");
} else {
System.out.println("correct, there are no numbers that are the same here");
}
}
private static boolean hasRepetitions(int[] a) {
int n = a.length;
for (int i = 0; i < n; i++) {
for (int j = i + 1; j < n; j++) {
if (a[i] == a[j]) {
return true;
}
}
}
return false;
}
}
I hope this will help...
Cheers,
Jeff
There are some flaws in your code:
This reads always the first element of the array: a[i] = Integer.parseInt(args[0]);, the boolean is never evaluated and the variable N is unnecessary (and in Java local variables should start with lower case).
I think, this is what you want:
int[] a = new int[args.length];
for (int i = 0; i < a.length; i++) {
a[i] = Integer.parseInt(args[i]);
}
for (int i = 0; i < a.length; i++) {
for (int j = i + 1; j < a.length; j++) {
if (a[i] == a[j]) {
System.out.print("same " + a[i]);
}
}
}
But a better way (as already mentioned) would be to use a HashSet. That way you do not even have to convert Strings to int. Just compare the values using equals() insted of ==. The code is even more simple:
public static void main(String[] args) {
java.util.Set<String> dbl = new java.util.HashSet<String>();
for (int i = 0; i < args.length; i++) {
for (int j = i + 1; j < args.length; j++) {
if (args[i].equals(args[j])) {
dbl.add(args[i]);
}
}
}
System.out.print("" + dbl.size() + " figure(s) appear more than once.");
java.util.Iterator<String> it = dbl.iterator();
while (it.hasNext()) {
System.out.print(" " + it.next());
}
}
public class SeeIT {
public static void main(String[] args) {
int [] a = new int[]{1,2,5,4,3,7,2};
boolean flag = false;
for(int i = 0; i< a.length; i++){
for(int j = 0; j< a.length; j++){
if(a[j] == a[i]){
if(j != i) {
flag = true;
}
}
}
}
if(flag == true){
System.out.println("Duplicates");
}else{
System.out.println("not duplicate");
}
}
}
}
This for-loop should do the trick. It's a double for-loop which iterates in the same array.
Related
Hi I'm trying to figure out how to use BubbleSort in Java and my code is erroring and I don't know why
import java.util.ArrayList;
public class SortsRunner {
public static void BubbleSort(ArrayList<Integer> nums) {
ArrayList<Integer> arr = new ArrayList<Integer>();
int n = arr.size();
for (int i = 0; i < n-1; i++)
for (int j = 0; j < n-i-1; j++)
if (arr.get(j) > arr.get(j+1))
{
int temp = arr.get(j);
arr.get(j) = arr.get(j+1);
arr.get(j+1) = temp;
}
}
public static void SelectionSort(ArrayList<Integer> nums) {
}
public static void printArrayList(ArrayList<Integer> nums) {
for(int i = 0; i < nums.size(); i++) {
System.out.println(nums.get(i) + " ");
}
System.out.println();
}
public static ArrayList<Integer> makeRandomArrayList() {
ArrayList<Integer> nums = new ArrayList<>();
for(int i = 0; i < (int)(Math.random() * 11) + 5; i++) {
nums.add((int)(Math.random() * 100));
}
return nums;
}
public static void main(String[] args) {
printArrayList(makeRandomArrayList());
}
}
When I get to arr.get(j) = arr.get(j+1); and arr.get(j+1) = temp; the left side errors saying "The left-hand side of an assignment must be a variable." can anyone help me fix this?
arr.get(j) = arr.get(j+1);
arr.get(j+1) = temp;
You're trying to assign a value to the result of a method call.
You just can't do this. You can only assign to a local variable, a field in the current class, a field access (e.g. foo.bar = ...) or an array element (e.g. foo[0] = ...).
Instead, you should use set to update a list element:
arr.set(j, arr.get(j+1));
arr.set(j+1, temp);
For the specific case of swapping two elements around in a list, you can instead use Collections.swap:
Collections.swap(arr, j, j+1);
You are doing several things wrong.
The obivous get and set issues already mentioned.
The fact that your are sorting an empty list. You pass in nums but sort the one you create which is empty.
You should use a boolean to prevent unnecessary repeats of the outer loop. Think of it like this, if you don't make a swap on the first iteration of the outer loop, then you won't swap on subsequent iterations.
And one style suggestion. Don't use loops or if statements without {}. Even if they only contain a single line of code. You will be less likely to make coding errors if you do so.
Try the following:
public static void BubbleSort(List<Integer> nums) {
int n = nums.size();
for (int i = 0; i < n; i++) {
boolean swapped = false;
for (int j = 0; j < n-1; j++) {
if (nums.get(j) > nums.get(j + 1)) {
int temp = nums.get(j);
nums.set(j, nums.get(j + 1));
nums.set(j + 1, temp);
swapped = true;
}
}
if (!swapped) {
break;
}
}
}
This question already has answers here:
Java: Print a unique character in a string
(20 answers)
Closed 4 years ago.
I am trying to print a character from a string which occurs only one time in the string. Here is the code I am using, but it is showing the answer always as H.
How can I fix this?
class StringRepeat {
static int i,j;
public static void main(String[] args) {
String s1 = "How are How";
outer:for(i=0;i<=s1.length(); i++)
{
inner:for(j=1;j<s1.length(); j++)
{
if (s1.charAt(i) != s1.charAt(j))
break outer;
}
}
System.out.println(s1.charAt(i));
}
}
Basically you can solve this in 2 ways - brute force (using arrays) and a bit more intelligently (using maps).
Brute force way
For every character in the input string check if it is the same as some other character:
public void uniqueCharsBruteForce(String input) {
for (int i = 0; i < input.length(); ++i) {
char candidate = input.charAt(i);
if (!contains(input, candidate, i)) {
System.out.println(candidate);
}
}
}
private boolean contains(String input, char candidate, int skipIndex) {
for (int i = 0; i < input.length(); ++i) {
if (i == skipIndex) {
continue;
}
if (candidate == input.charAt(i)) {
return true;
}
}
return false;
}
Code is simple but very slow, so use only for short strings. Time complexity is O(n^2).
Using maps
As you iterate through the input, count how many times each character appears. At the end, print only those who appear once only:
public void uniqueCharsBetter(String input) {
Map<Character, Integer> occurences = new HashMap<>();
for (int i = 0; i < input.length(); ++i) {
Character key = Character.valueOf(input.charAt(i));
occurences.put(key, occurences.getOrDefault(key, 0) + 1);
}
occurences.entrySet().forEach(entry -> {
if (entry.getValue().intValue() == 1) {
System.out.println(entry.getKey());
}
});
}
This can be optimized further but it's possible this is enough for your requirements. Time complexity is O(n).
This will give an StringIndexOutOfBoundsException if no unique
char is found:
outer:for(i=0;i<=s1.length(); i++)
replace it with
int i = 0;
outer: for(;i<s1.length(); i++)
There's no need for an inner label, and you need to start the search
from 0, not 1, so replace
inner:for(j=1;j<s1.length(); j++)
with
for(int j=0;j<s1.length(); j++)
You have your test inverted. If the characters at i and j are
the same, you need to continuue with the outer loop. Also, you need to
make sure you don't compare when i==j. So your test changes from:
if (s1.charAt(i) != s1.charAt(j))
break outer;
to
if (i!=j && s1.charAt(i) == s1.charAt(j))
continue outer;
If the inner for loop terminates, i.e. gets to the end of the
string, then the character at i is unique, so we need to break out
of the outer loop.
When you exit the outer loop you need to determine if you found a unique element, which will be the case if i < s1.length().
Putting this all together we get:
String s1= "How are How";
int i = 0;
outer: for(;i<s1.length(); i++)
{
for(int j=0;j<s1.length(); j++)
{
if (i!=j && s1.charAt(i) == s1.charAt(j))
continue outer;
}
break;
}
if(i<s1.length()) System.out.println(s1.charAt(i));
Here a link to the code (IDEOne).
This will print out every character that appears only once in the text.
final String s1 = "How are How";
outer:for(int i = 0; i < s1.length(); i++)
{
for(int j = 0; j < s1.length(); j++)
{
if(s1.charAt(i) == s1.charAt(j) && i != j)
{
continue outer;
}
}
System.out.println(s1.charAt(i);
}
Try this
String s = inputString.toLowerCase();
boolean[] characters = new boolean[26];
for(int i = 0; i < 26; i++)
characters[i] = true;
for(int i = 0; i < s.length(); i++)
{
if(characters[s.charAt(i) - 'a'])
{
System.out.println(s.charAt(i));
characters[s.charAt(i) - 'a'] = false;
}
}
Hope this helps. I have assumed that u treat lowercase and uppercase as same else u can modify accordingly
I can't wrap my head around this. Need to find duplicates and I did. All now that is left is to print how many times a duplicate appears in the array. I just started with Java,so this needs to be hard coded for me to understand. Spend last two days trying to figure it out but with no luck.. Any help will be great! Talk is cheap,here is the code..
import java.util.Arrays;
public class LoopTest {
public static void main(String[] args) {
int[] array = {12,23,-22,0,43,545,-4,-55,43,12,0,-999,-87};
int positive_counter = 0;
int negative_counter = 0;
for (int i = 0; i < array.length; i++) {
if(array[i] > 0) {
positive_counter++;
} else if(array[i] < 0) {
negative_counter++;
}
}
int[] positive_array = new int[positive_counter];
int[] negative_array = new int[negative_counter];
positive_counter = 0;
negative_counter = 0;
for (int i = 0; i < array.length; i++) {
if(array[i] > 0) {
positive_array[positive_counter++] = array[i];
} else if(array[i] < 0) {
negative_array[negative_counter++] = array[i];
}
}
System.out.println("Positive array: " + (Arrays.toString(positive_array)));
System.out.println("Negative array: " + (Arrays.toString(negative_array)));
Arrays.sort(array);
System.out.println("Array duplicates: ");
for (int i = 0; i < array.length; i++) {
for (int j = i + 1; j < array.length; j++) {
if(array[i] == array[j]) {
System.out.println(array[j]);
}
}
}
}
}
Since you are already sorting the array you can find the duplicates with just one loop (they will be next to each other right?). So you can do something like:
Arrays.sort(array);
System.out.println("Array duplicates: ");
int lastValueCount=1; //How many times we met the current value (at least 1 - this time)
for (int i = 1; i < array.length; i++){
if(array[i] == array[i-1])
lastValueCount++; //If it is the same as the previous increase the count
else {
if(lastValueCount>1) //If it is duplicate print it
System.out.println(array[i-1]+" was found "+lastValueCount+" times");
lastValueCount=1; //reset the counter
}
}
Result for your array is:
Array duplicates:
0 was found 2 times
12 was found 2 times
43 was found 2 times
Also you can use some of the Java bells and whistles like inserting the values into Map or something like that but I guess you are looking from an algorithmic point of view so the above is the simple answer with just one loop
Just go through your solution, first you separate positive and negative numbers in two different arrays, then you never use them, so what's the purpose of this separation ?
I am giving you just an idea related to your problem, it's better to solve it by your self so that you can get hands on Java.
Solution: you can use Dictionary-key value pair. Go through your array, put element in dictionary as a key and value as zero, on every iteration check if that key already exist in Dictionary, just increment its value. In the end, all of the values are duplicates that occurs in your array.
Hope it helps you.
From the algorithmic point of view, Veselin Davidov's answer is good (the most efficient).
In a production code, you would rather write it like this :
Map<Integer, Long> result =
Arrays.stream(array)
.boxed() //converts IntStream to Stream<Int>
.collect(Collectors.groupingBy(i -> i, Collectors.counting()));
The result is this Map :
System.out.println(result);
{0=2, 545=1, -4=1, -22=1, -87=1, -999=1, -55=1, 23=1, 43=2, 12=2}
An easy way would be using Maps. Without changing code too much:
for (int i = 0; i < array.length; i++) {
int count = 0;
for (int j = i + 1; j < array.length; j++) {
if(array[i] == array[j]) {
System.out.println(array[j]);
count++;
}
}
map.put(array[i], count);
}
Docs:
https://docs.oracle.com/javase/7/docs/api/java/util/Map.html
Edit: As a recommendation, after you are done with the example, you should analize your code and find what isnĀ“t neccesary, what could be done better, etc.
Are all your auxiliary arrays neccesary? Are all loops necessary?
You can do it by creating an array list for duplicate values:-
Arrays.sort(array);
System.out.println("Array duplicates: ");
ArrayList<Integer> duplicates = new ArrayList<Integer>();
for (int i = 0; i < array.length; i++) {
for (int j = 0; j < array.length; j++) {
if(j != i && array[i] == array[j] && !duplicates.contains(array[i])){
duplicates.add(array[i]);
System.Out.println(duplicates[duplicates.size()-1]);
}
}
}
public static void findDuplicate(String s){
char[] charArray=s.toCharArray();
ArrayList<Character> duplicateList = new ArrayList<>();
System.out.println(Arrays.toString(charArray));
for(int i=0 ; i<=charArray.length-1; i++){
if(duplicateList.contains(charArray[i]))
continue;
for(int j=0 ; j<=charArray.length-1; j++){
if(i==j)
continue;
if(charArray[i] == charArray[j]){
duplicateList.add(charArray[j]);
System.out.println("Dupliate at "+i+" and "+j);
}
}
}
}
i have an array of integers like this one :
A={1,1,4,4,4,1,1}
i want to count the each number once , for this example the awnser is 2 becuase i want to count 1 once and 4 once
i dont want to use sorting methods
i am unable to find a way to solve it using java.
i did this but it gives me 0
public static void main(String args[]) {
int a[] = { 1,1,4,4,4,4,1,1};
System.out.print(new Test4().uniques(a));
}
public int uniques(int[] a) {
int unique = 0;
int tempcount = 0;
for (int i = 0; i < a.length; i++) {
for (int j = 0; j < a.length; j++) {
if (a[i] == a[j]) {
tempcount++;
}
}
if (tempcount <= 2) {
unique=a[i];
}
tempcount = 0;
}
return unique;
}
the purpose of the question is to understand the logic of it but not solving it using ready methods or classes
This one should work. I guess this might be not the most elegant way, but it is pretty straightforward and uses only simple arrays. Method returns number of digits from array, but without counting duplicates - and this I believe is your goal.
public int uniques(int[] a) {
int tempArray[] = new int[a.length];
boolean duplicate = false;
int index = 0;
int digitsAdded = 0;
for (int i = 0; i < a.length; i++) {
for (int j = 0; j < tempArray.length; j++) {
if (a[i] == tempArray[j]) {
duplicate = true;
}
}
if(!duplicate) {
tempArray[index] = a[i];
index++;
digitsAdded++;
}
duplicate = false;
}
//this loop is needed if you have '0' in your input array - when creating temp
//array it is filled with 0s and then any 0 in input is treated as a duplicate
//again - not most elegant solution, maybe I will find better later...
for(int i = 0; i < a.length; i++) {
if(a[i] == 0) {
digitsAdded++;
break;
}
}
return digitsAdded;
}
Okay first of all in your solution you are returning the int unique, that you are setting as the value that is unique a[i]. So it would only return 1 or 4 in your example.
Next, about an actual solution. You need to check if you have already seen that number. What you need to check is that for every number in the array is only appears in front of your position and not before. You can do this using this code below.
public int uniques(int[] a) {
int unique = 1;
boolean seen = false;
for (int i = 1; i < a.length; i++) {
for (int j = 0; j < i; j++) {
if (a[i] == a[j]) {
seen = true;
}
}
if (!seen) {
unique++;
}
seen = false;
}
return unique;
}
In this code you are iterating over the number you have seen and comparing to the number you are checking (a[i]). You know that for it to be unique you cant have seen it before.
I see two possible solutions:
using set
public int unique(int[] a) {
Set<Integer> set = new HashSet<>();
for (int i : a) {
set.add(i);
}
return set.size();
}
using quick sort
public int unique(int[] a) {
Arrays.sort(a);
int cnt = 1;
int example = a[0];
for (int i = 1; i < a.length; i++) {
if (example != a[i]) {
cnt++;
example = a[i];
}
}
return cnt;
}
My performance tests say that second solution is faster ~ 30%.
if restricted to only arrays, consider trying this:
Lets Take a temporary array of the same size of orignal array, where we store each unique letter and suppose a is your orignal array,
int[] tempArray= new int[a.length];
int tempArraycounter = 0;
bool isUnique = true;
for (int i = 0; i < a.length; i++)
{
isUnique = true;
for (int j = 0; j < tempArray.length; j++)
{
if(tempArray[j] == a[i])
isUnique = false;
}
if(isUnique)
{
tempArray[tempArraycounter] = a[i];
tempArraycounter++;
isUnique = false;
}
}
now tempArraycounter will be your answer ;)
Try Following code:
int test[]={1,1,4,4,4,1,1};
Set<Integer> set=new LinkedHashSet<Integer>();
for(int i=0;i<test.length;i++){
set.add(test[i]);
}
System.out.println(set);
Output :
[1, 4]
At the end set would contain unique integers.
This question already has answers here:
How to get unique values from array
(13 answers)
Closed 8 years ago.
void RemoveDups(){
int f=0;
for(int i=1;i<nelems;i++){
if(arr[f]==arr[i]){
for(int k=i;k<nelems;k++)
{
arr[k]=arr[k+1];
}
nelems--;
}
if(i==(nelems+1)){
f++;
i=f+1; //increment again
}
}
}
This is the logic i have written to remove duplicate elements from an array ,but this is not working at all ?what changes i should make to make it work? or you people have better logic for doing the same considering time complexity.and i don't want to use built-in methods to achieve this.
int end = input.length;
for (int i = 0; i < end; i++) {
for (int j = i + 1; j < end; j++) {
if (input[i] == input[j]) {
int shiftLeft = j;
for (int k = j + 1; k < end; k++, shiftLeft++) {
input[shiftLeft] = input[k];
}
end--;
j--;
}
}
}
I think you can use Set Collection
copy all the values to an HashSet and then using Iterator access the Values
Set<Integer> hashset= new HashSet<Integer>();
You have two options, C# has the Distinct() Linq expression that will do this for you (Missed the Java tag), however if you need to remove items, have you thought about sorting the list first, then comparing the current item to the previous item and if they're the same, remove them. It would mean your diplicate detection is only ever running through the array once.
If you're worried about sort you could easily implement an efficient bubble sort or somthing to that effect
You never decrease i after You compared for examlpe arr[0] to arr[5], You never will test arr[1] == arr[2]
You need to start a new loop (i) after You've incremented f.
try
for(int f=0;f<nelems-1;f++)
{
for(int i=f+1;i<nelems;i++)
{
...
}
}
with this nested for loop you can compare every two element of the array.
a good start is to eliminate duplicate elements without shrinking the array which is done lastly:
public class run2 extends Thread {
public static void main(String[] args) {
int arr[] = { 1, 2, 2, 3, 5, 6, 5, 5, 6, 7 };
for (int i = 0; i < arr.length; i++) {
for (int j = i + 1; j < arr.length; j++) {
if (arr[j] == -1)
j++;
if (arr[i] == arr[j])
arr[j] = -1;
}
}
for (int i = 0; i < arr.length; i++) {
System.out.print(arr[i] + ",");
}
System.out.println();
for (int i = 0; i < arr.length; i++) {
if (arr[i] == -1) {
for (int j = i; j < arr.length; j++) {
if (arr[j] != -1) {
arr[i] = arr[j];
arr[j] = -1;
break;
}
}
}
}
for (int i = 0; i < arr.length; i++) {
System.out.print(arr[i] + ",");
}
}
}
Adapt this code :
public static int[] removeDuplicates(int[] numbersWithDuplicates) {
// Sorting array to bring duplicates together
Arrays.sort(numbersWithDuplicates);
int[] result = new int[numbersWithDuplicates.length];
int previous = numbersWithDuplicates[0];
result[0] = previous;
for (int i = 1; i < numbersWithDuplicates.length; i++) {
int ch = numbersWithDuplicates[i];
if (previous != ch) {
result[i] = ch;
}
previous = ch;
}
return result;
}
As far as I understood from your code,you are comparing each value starting from index 0 to the rest of the element and when you see the element which is located at index f your are trying to shift the entire array and decrementing the size of array(nelems).Look at line no. 11
if(i==(nelems+1)){
f++;
i=f+1;
The problem is when i is set to f+1,i will again be incremented in the for loop for the next iteration.So basically i starts comparing from f+2.And also you are comparing i with (nelems+1) considering the case when nelems decremented but you are not considering the case when i reaches the end without decreasing nelems in that case i will never be equale to (nelems+1).Now considering your logic you could do 2 things.
1.Here is your working code.
for(int i=1;i<nelems;i++){
if(arr[f]==arr[i]){
for(int k=i+1;k<nelems;k++)
{
arr[k-1]=arr[k];
}
if(i==(nelems-1)){
f++;
i=f;
}
nelems--;
}
if(i==(nelems-1)){//end of the loop
f++;
i=f; //increment again
}
}
2.You could use an outer for loop alternatively that will increment the f value once the inner for is completed.
void RemoveDups(){
for(int f=0;f<nelems;++f){
for(int i=1;i<nelems;i++){
if(arr[f]==arr[i]){
for(int k=i;k<nelems;k++)
arr[k]=arr[k+1];
nelems--;
}
}
}
}
Now your problem is solved but the time complexity of your code will be(O(N^3)).
Now instead of shifting the entire array at line 4,you could just swap the arr[f] with last element.
if(arr[f]==arr[i]){
swap(arr[f],arr[nelems-1]);
nelems--;
}
it will reduce the time complexity from O(N^3) to O(N^2).
Now I'll suggest you my method
1.just sort the array.It will be done in O(NlogN).
2.now using one for loop you can get what do you wanted.
void RemoveDups(){
int k=0,i;
for(i=1;i<nelems;++i){
while(arr[i]==arr[i-1])
++i;
arr[k++]=arr[i-1];
}
arr[k++]=arr[i-1];
}
Now basically you got an array of size k,which contains non repeated element in sorted order and the time complexity of my solution is O(NlogN).