Find the last occurrence of an array Java? - java

I'm new to Java. I would like to get the index of the last occurrence in an array using loop. However, I don't understand why I can't.
This is the array:
{2, 3, 4, 5, 4, 5, 3}
I would like to get the index of the last 4 in it.
My code is:
public static void main(String args[]){
int[] nums = {2, 3, 4, 5, 4, 5, 3};
int pos4 = 0;
for (int k = nums.length -1; k >= 0; k--){
if (nums[k] == 4){
pos4 = k;
break;
}
System.out.print(pos4);
}
}
The result is: 00 ??
When I change to:
public static void main(String args[]){
int[] nums = {2, 3, 4, 5, 4, 5, 3};
int pos4 = 0;
for (int k = nums.length -1; k >= 0; k--){
if (nums[k] == 4){
break;
}
System.out.print(k);
}
}
I got 65 ???
However, when I print directly from the loop I get the index correctly:
public static void main(String args[]){
int[] nums = {2, 3, 4, 5, 4, 5, 3};
int pos4 = 0;
for (int k = nums.length -1; k >= 0; k--){
if (nums[k] == 4){
System.out.print(k);
break;
}
}
}
Can anyone tell me why? Thanks a lot!

Your first example is printing from within the loop. Once the condition was met you exited the loop and never printed out the final value.
public static void main(String args[]){
int[] nums = {2, 3, 4, 5, 4, 5, 3};
int pos4 = 0;
for (int k = nums.length -1; k >= 0; k--) {
if (nums[k] == 4){
pos4 = k;
break;
}
}
System.out.print(pos4); // moved outside of loop to print final value
}

How about using existing methods, and not reinventing the wheel? this one-liner solves the problem:
Integer[] array = { 2, 3, 4, 5, 4, 5, 3 };
int idx = Arrays.asList(array).lastIndexOf(4);

Your print statement is inside the loop. So it prints 0 twice, then when the result is found the break; skips over it. Try this...
int pos4 = 0;
for (int k = nums.length - 1; k >= 0; k--) {
if (nums[k] == 4) {
pos4 = k;
break;
}
}
System.out.print(pos4); // <== after loop

Related

JAVA/Selection sort : the console shows different results from what I've entered

I'm learning how to implement selection sort.
What I expected from the code is an ascending order output, like: {1,3,4,5,6,7,9}
But the console showed: 9, 4, 1, 6, 5, 3, 7, 9, 7, 1, 4, 5, 3, 6, 9, 7, 6, 1, 4, 3, 5, 9, 7, 6, 5, 1, 3, 4, 9, 7, 6, 5, 4, 1, 3, 9, 7, 6, 5, 4, 3, 1
What am I supposed to change to get the correct result?
This is my code:
public static void main(String[] args) {
int[]arr = {4,6,1,9,5,3,7};
for(int i = 0; i<arr.length-1; i++) {
for(int j = i+1; j<arr.length; j++) {
if(arr[i]<arr[j]) {
int a=arr[i];
arr[i]=arr[j];
arr[j]=a;
}
}
for (int b = 0; b <arr.length; b++) {
System.out.print(arr[b] + ", ");
}
}
You are printing the array while you are doing the sorting. Instead, print the array when you are done with the sorting -
public static void main(String[] args) {
int[] arr = {4, 6, 1, 9, 5, 3, 7};
for (int i = 0; i < arr.length - 1; i++) { // first loop
for (int j = i + 1; j < arr.length; j++) { // nested loop
if (arr[i] < arr[j]) { // if condition
int a = arr[i];
arr[i] = arr[j];
arr[j] = a;
} // if condition ends
} // nested loop ends
} // first loop ends
// Now the array is sorted, it's good to print.
for (int b = 0; b < arr.length; b++) {
System.out.print(arr[b] + ", ");
}
}
There is one more catch. Though your sorting would work, your implementation is not really selection sort. It's bubble sort implementation. The key difference is, in selection sort you need to find the min value and place it in the ith position for every i. So you only swap once per iteration. In bubble sort, we swap repeatedly like you did.
Also, as pointed out in the comment, for ascending order, you have to flip to condition for swapping. So the correct implementation would be -
public static void main(String[] args) {
int[] arr = {4, 6, 1, 9, 5, 3, 7};
for (int i = 0; i < arr.length - 1; i++) {
int minIndex = i;
for (int j = i + 1; j < arr.length; j++) {
if (arr[minIndex] > arr[j]) {
minIndex = j;
}
}
int tmp = arr[i];
arr[i] = arr[minIndex];
arr[minIndex] = tmp;
}
for (int b = 0; b < arr.length; b++) {
System.out.print(arr[b] + ", ");
}
}
There is an easier way with Arrays.sort(arr)
public static void main(String[] args) {
int[] arr = {4,6,1,9,5,3,7};
Arrays.sort(arr);
System.out.print(Arrays.toString(arr));
}
}
Selection Sort - java code
class selectionsort{
public static void sort(int[] arr){
int temp,min;
for(int i=0;i<arr.length;i++)
{
min=i;
for(int j=i+1;j<arr.length;j++)
{
if(arr[min]>arr[j])
{
min=j;
}
}
temp=arr[min];
arr[min]=arr[i];
arr[i]=temp;
}
}
public static void main(String [] args){
int ar[]={4,6,1,9,5,3,7};
sort(ar);
System.out.print("After sort :");
for(int j=0;j<ar.length;j++){
System.out.print(ar[j]+" ");
}
}
}

Combine two int arrays without duplicates using only for loops

This is a pretty beginner assignment, and I would love to get some help with my code.
I need to combine two integer arrays into one using for loops, and make sure I don't have duplicates. Anything I googled is pretty over complicated and uses all sorts of built in methods.
Here is my code:
static void SumArray(){
int[] array1 = { 1, 2, 3 };
int[] array2 = { 3, 4, 5 };
int[] merged = new int[array1.length + array2.length];
int pos = 0;
for (int i = 0; i < array1.length; i++) {
merged[pos] = array1[i];
pos++;
}
for (int j = merged[pos]; j < array2.length; j++) {
if (merged[pos] != array2[j]) {
merged[pos] = array2[j];
pos++;
}
}
System.out.println(Arrays.toString(merged));
Ultimately, it should return {1, 2, 3, 4, 5}. Instead, currently it returns 1, 2, 3, 3, 4, 5.
I would like to know why my if doesn't work. It should skip the 3 since it is already in there.
What am I missing?
Thanks :)
Edit:
Thanks guys, this is what I ended up doing, which still isn't good since I'm not checking for duplicates in the first loop that goes over the first array:
static void SumArray(){
int[] array1 = { 1, 2, 3 };
int[] array2 = { 3, 4, 5 };
int arrSize = array1.length + array2.length;
int[] merged = new int[arrSize];
int pos = 0;
int counter = 0;
for (int i = 0; i < array1.length; i++) {
merged[pos] = array1[i];
pos++;
}
for (int j = merged[pos]; j < array2.length; j++) {
if (merged[pos-1] != array2[j]) {
merged[pos] = array2[j];
pos++;
counter++;
}
}
int[] newMerged = new int[arrSize - counter + 1];
System.arraycopy(merged, 0, newMerged, 0, newMerged.length);
System.out.println(Arrays.toString(newMerged));
}
I'm sure I'll find a way.
I would like to know why my if doesn't work.
Because merged[pos] is always 0, because you've never assigned any other value to it in your code. Array entries are initialized to zero when you create the array.
You can't just check one entry to know whether to add a value from array2. You have to check all of the entries you've written, with a nested loop within your second for loop. Only add a new entry if it isn't already there.
Note that you'll also need to either check ahead of time how many duplicates there are so you know that merged should only be 5 entries long, or you need to re-create merged later when you know how long it should be. Otherwise, your end result will be {1, 2, 3, 4, 5, 0}, not {1, 2, 3, 4, 5}.
because of the "pos++" in the first for loop as you are using as start index of j in the second loop.
Your 3 is in the index 2 and you are comparing it to index 3, which never be equal
here is your answer:
int[] array1 = { 1, 2, 3 };
int[] array2 = { 3, 4, 5 };
int[] merged = new int[array1.length + array2.length];
int pos = 0,i=0, j;
Set<Integer> intSet = new HashSet();
for (i = 0; i < array1.length; i++) {
if(!intSet.contains(array1[i])) {
merged[pos] = array1[i];
intSet.add(Integer.valueOf(i));
pos++;
}
}
for (j= 0, pos = pos-1; j < array2.length; ) {
if(!intSet.contains(Integer.valueOf(array2[j]))) {
merged[pos] = array2[j];
intSet.add(Integer.valueOf(i));
pos++;
j++;
}
}
System.out.println(Arrays.toString(merged));
Here is solution for Java 8 and bigger version:
int[] first = { 1, 2, 3 };
int[] second = { 3, 4, 5 };
int[] merged = Stream.of(first, second)
.flatMapToInt(Arrays::stream)
.distinct()
.toArray();

Sorting list of numbers

I am trying to sort a list of numbers from smallest to the biggest and print it. I've tried two things:
1.
public class Sorter {
public static void main(String[] args) {
int[] numbers = {1, 3, 8, 2, 5, -2, 0, 7, 15};
int[] sorted = new int[numbers.length];
for (int a = 0; a < numbers.length; a++) {
int check = 0;
for (int b = 0; b < numbers.length; b++) {
if (numbers[a] < numbers[b]) {
check++;
}
}
sorted[check] = numbers[a];
}
for (int c = numbers.length - 1; c >= 0; c--) {
System.out.print(sorted[c] + ", ");
}
}
}
and this thing works, but won't work with repeated values, so I tried this other thing
public class Sortertwo {
public static void main(String[] args) {
int[] numinput = {3, 2, 1, 4, 7, 3, 17, 5, 2, 2, -2, -4};
int[] numsorted = new int[numinput.length];
int n = 0;
for (; n < numinput.length; ) {
for (int b = 0; b < numinput.length; b++) {
int check = 0;
for (int c = 0; c < numinput.length; c++) {
if (numinput[b] <= numinput[c]) {
check++;
}
}
if (check >= (numinput.length - n) && numinput[b] != 0) {
numsorted[n] = numinput[b];
numinput[b] = 0;
n++;
}
if (n >= (numinput.length)) {
break;
}
}
}
for (int g = 0; g < numinput.length; g++) {
System.out.print(numsorted[g] + ", ");
}
}
}
Where it relies on the thing that once the number from the first array is used (the smallest one is found), it has to be ignored when the program goes through the array next time around.
I tried to assign it like null value, but it doesn't work, so I assigned it to zero and then ignore it, which is a problem, because the list cant have a zero in it.
Is there any like better way to go about it? Thanks.
You can always use:
Arrays.sort(numbers);
If you want to use your first method then change this:
if (numbers[a] < numbers[b])
{
check++;
}
to:
if (numbers[a] <= numbers[b])
{
check++;
}
Unless this is homework, using Arrays.sort as the comments suggest, should be the way to go
import java.util.Arrays;
public class S {
public static void main(String ... args) {
int[] numbers = {1, 3, 8, 2, 5, -2, 0, 7, 15};
Arrays.sort(numbers);
System.out.println(Arrays.toString(numbers));
}
}
Prints:
[-2, 0, 1, 2, 3, 5, 7, 8, 15]

Duplicate array elements and unique elements

So, i am writing a program that analyzes an entire array and displays the repeated values as well as the unique values:
int dupe = 0;
int[] range = {1, 1, 2, 2, 2, 3, 3, 3, 4, 5, 6, 6};
for (int i = 0; i < range.length; i++) {
for (int j = i + 1; j < range.length; j++) {
if (range[i] == range[j]) {
dup = range[j];
System.out.println(dup);
}
}
}
The above code outputs the repeated values correctly but when the value repeats three or more times, it outputs that value many times instead of just once
1
2
2
2
3
3
3
6
How can i fix this?
For the unique value part of the program, i don't know where to start.
Thanks!
EDIT: The only Arrays class methods i can use are: binarySearch, copyOf, equals, fill, sort, and toString
I need to write my own implementation - not to use Set, HashSet etc. Or any other tools such as iterators
You can do somthing like bellow:
int[] range = {1, 1, 2, 2, 2, 3, 3, 3, 4, 5, 6, 6};
boolean duplicate = false;
for (int i = 0; i < range.length; i++) {
duplicate = false;
for (int j = i + 1; j < range.length; j++) {
if (range[i] == range[j]) {
duplicate = true
}
}
if(!duplicate){
System.out.println(range[i]);
}
}
You can add your values to Set. it will do all work for you.
int end = arr.length;
Set<Integer> set = new HashSet<Integer>();
for(int i = 0; i < end; i++){
set.add(arr[i]);
}
If you cannot use other data structures, here is a good solution: https://stackoverflow.com/a/17974322/2290763
Other solution are correct but they will give O(n^2), you don't need to use two for loops. This will give you O(n)
int[] range = {1, 1, 2, 2, 2, 3, 3, 3, 4, 5, 6, 6};
int temp = range[0];
if(temp != range[range.length-1]){
for (int i = 1; i < range.length; i++) {
if(temp != range[i]){
System.out.println(temp);
temp = range[i];
}
}
}
else
System.out.println(temp);
Try after sorting the array:
int[] range = { 1, 1, 2, 2, 2, 3, 3, 3, 4, 5, 6, 6 };
Arrays.sort(range);
System.out.println(range.length > 0 ? range[0]
: "No sufficient elements");
for (int i = 1; i < range.length; i++) {
if (range[i - 1] != range[i]) {
System.out.println(range[i]);
}
}
Each value in the array is either unique or occurs multiple times. There are no other cases.
So your task can be stripped down to just remove the duplicates and print everything else.
If the array is sorted then it is sufficient to just check against the last value while iterating to recognize duplicates.
I would do this:
int[] range = {1, 1, 2, 2, 2, 3, 3, 3, 4, 5, 6, 6};
Arrays.sort(range);
for (int i = 0; i < range.length; i++) {
if (i == 0) {
System.out.println(range[0]);
} else if (range[i - 1] != range[i]) {
System.out.println(range[i]);
}
}
Edited. Try this:
int[] range = { 1, 1, 2, 2, 2, 3, 3, 3, 4, 5, 6, 6};
for (int i = 0; i < range.length; i++) {
int j = i + 1;
for (; j < range.length && range[i] == range[j]; j++) {
// do nothing
}
if (j >= i + 2) {
System.out.println(range[i]);
i = j;
}
}
}
The problem in your solution is int this part
for (int i = 0; i < range.length; i++) {
for (int j = i + 1; j < range.length; j++) {
For every element in array you are checking is there element with same value, and index is greater than index of element.
For example, for element with index 2 (value 2) it's checking all (indexes: 3, 4, 5, 6, ...). And there are two matches (elements with index 3 and 4).
Edit: (After #FabianBarney comment)
Solution:
String uni = "Uniques: ";
String dup = "Duplicates: ";
int[] range = { 1, 1, 2, 2, 2, 3, 3, 3, 4, 5, 6, 6};
for (int i = 0; i < range.length; i++) {
if (i + 1 < range.length && range[i + 1] == range[i]) {
dup += range[i] + " ";
int j = i + 1;
while (j < range.length && range[i] == range[j]) {
j++;
}
i = j - 1;
} else {
uni += range[i] + " ";
}
}
System.out.println(uni);
System.out.println(dup);

How to get unique items from an array?

I am Java beginner, I found a few topics regarding this theme, but none of them worked for me.
I have an array like this:
int[] numbers = {1, 1, 2, 1, 3, 4, 5};
and I would need to get this output:
1, 2, 3, 4, 5
Every item from that array just once.
But how to get it?
The simpliest solution without writing your own algorithm:
Integer[] numbers = {1, 1, 2, 1, 3, 4, 5};
Set<Integer> uniqKeys = new TreeSet<Integer>();
uniqKeys.addAll(Arrays.asList(numbers));
System.out.println("uniqKeys: " + uniqKeys);
Set interface guarantee uniqueness of values. TreeSet additionally sorts this values.
You can use a Set<Integer> and save lot of time since it holds unique elements. If you aren't allowed to use any class from Java Collections, sort the array and count the unique elements. You can sort the array manually or use Arrays#sort.
I'll post the Set<Integer> code:
int[] numbers = {1, 1, 2, 1, 3, 4, 5};
Set<Integer> setUniqueNumbers = new LinkedHashSet<Integer>();
for(int x : numbers) {
setUniqueNumbers.add(x);
}
for(Integer x : setUniqueNumbers) {
System.out.println(x);
}
Note that I prefer to use LinkedHashSet as Set implementation since it maintains the order of how the elements were inserted. This means, if your array was {2 , 1 , 2} then the output will be 2, 1 and not 1, 2.
In Java 8:
final int[] expected = { 1, 2, 3, 4, 5 };
final int[] numbers = { 1, 1, 2, 1, 3, 4, 5 };
final int[] distinct = Arrays.stream(numbers)
.distinct()
.toArray();
Assert.assertArrayEquals(Arrays.toString(distinct), expected, distinct);
final int[] unorderedNumbers = { 5, 1, 2, 1, 4, 3, 5 };
final int[] distinctOrdered = Arrays.stream(unorderedNumbers)
.sorted()
.distinct()
.toArray();
Assert.assertArrayEquals(Arrays.toString(distinctOrdered), expected, distinctOrdered);
//Running total of distinct integers found
int distinctIntegers = 0;
for (int j = 0; j < array.length; j++)
{
//Get the next integer to check
int thisInt = array[j];
//Check if we've seen it before (by checking all array indexes below j)
boolean seenThisIntBefore = false;
for (int i = 0; i < j; i++)
{
if (thisInt == array[i])
{
seenThisIntBefore = true;
}
}
//If we have not seen the integer before, increment the running total of distinct integers
if (!seenThisIntBefore)
{
distinctIntegers++;
}
}
Below code will print unique integers have a look:
printUniqueInteger(new int[]{1, 1, 2, 1, 3, 4, 5});
static void printUniqueInteger(int array[]){
HashMap<Integer, String> map = new HashMap();
for(int i = 0; i < array.length; i++){
map.put(array[i], "test");
}
for(Integer key : map.keySet()){
System.out.println(key);
}
}
Simple Hashing will be far efficient and faster than any Java inbuilt function:
public class Main
{
static int HASH[];
public static void main(String[] args)
{
int[] numbers = {1, 1, 2, 1, 3, 4, 5};
HASH=new int[100000];
for(int i=0;i<numbers.length;i++)
{
if(HASH[numbers[i]]==0)
{
System.out.print(numbers[i]+",");
HASH[numbers[i]]=1;
}
}
}
}
Time Complexity: O(N), where N=numbers.length
DEMO
public class Practice {
public static void main(String[] args) {
List<Integer> list = new LinkedList<>(Arrays.asList(3,7,3,-1,2,3,7,2,15,15));
countUnique(list);
}
public static void countUnique(List<Integer> list){
Collections.sort(list);
Set<Integer> uniqueNumbers = new HashSet<Integer>(list);
System.out.println(uniqueNumbers.size());
}
}
In JAVA8, you can simply use
stream()
and
distinct()
to get unique elements.
intArray = Arrays.stream(intArray).distinct().toArray();
There is an easier way to get a distinct list:
Integer[] intArray = {1,2,3,0,0,2,4,0,2,5,2};
List<Integer> intList = Arrays.asList(intArray); //To List
intList = new ArrayList<>(new LinkedHashSet<>(intList)); //Distinct
Collections.sort(intList); //Optional Sort
intArray = intList.toArray(new Integer[0]); //Back to array
Outputs:
1 2 3 0 0 2 4 0 2 5 2 //Array
1 2 3 0 0 2 4 0 2 5 2 //List
1 2 3 0 4 5 //Distinct List
0 1 2 3 4 5 //Distinct Sorted List
0 1 2 3 4 5 //Distinct Sorted Array
See jDoodle Example
You could do it like this:
int[] numbers = {1, 1, 2, 1, 3, 4, 5};
ArrayList<Integer> store = new ArrayList<Integer>(); // so the size can vary
for (int n = 0; n < numbers.length; n++){
if (!store.contains(numbers[n])){ // if numbers[n] is not in store, then add it
store.add(numbers[n]);
}
}
numbers = new int[store.size()];
for (int n = 0; n < store.size(); n++){
numbers[n] = store.get(n);
}
Integer and int can be (almost) used interchangeably. This piece of code takes your array "numbers" and changes it so that all duplicate numbers are lost. If you want to sort it, you can add Collections.sort(store); before numbers = new int[store.size()]
I don't know if you've solved your issue yet, but my code would be:
int[] numbers = {1, 1, 2, 1, 3, 4, 5};
int x = numbers.length;
int[] unique = new int[x];
int p = 0;
for(int i = 0; i < x; i++)
{
int temp = numbers[i];
int b = 0;
for(int y = 0; y < x; y++)
{
if(unique[y] != temp)
{
b++;
}
}
if(b == x)
{
unique[p] = temp;
p++;
}
}
for(int a = 0; a < p; a++)
{
System.out.print(unique[a]);
if(a < p-1)
{
System.out.print(", ");
}
}
String s1[]= {"hello","hi","j2ee","j2ee","sql","jdbc","hello","jdbc","hybernet","j2ee"};
int c=0;
for(int i=0;i<s1.length;i++)
{
for(int j=i+1;j<s1.length;j++)
{
if(s1[i]==(s1[j]) )
{
c++;
}
}
if(c==0)
{
System.out.println(s1[i]);
}
else
{
c=0;
}
}
}
}
To find out unique data:
public class Uniquedata
{
public static void main(String[] args)
{
int c=0;
String s1[]={"hello","hi","j2ee","j2ee","sql","jdbc","hello","jdbc","hybernet","j2ee","hello","hello","hybernet"};
for(int i=0;i<s1.length;i++)
{
for(int j=i+1;j<s1.length;j++)
{
if(s1[i]==(s1[j]) )
{
c++;
s1[j]="";
}}
if(c==0)
{
System.out.println(s1[i]);
}
else
{
s1[i]="";
c=0;
}
}
}
}
you can use
Object[] array = new HashSet<>(Arrays.asList(numbers)).toArray();
Here is my piece of code using counting sort (partially)
Output is a sorted array consiting of unique elements
void findUniqueElementsInArray(int arr[]) {
int[] count = new int[256];
int outputArrayLength = 0;
for (int i = 0; i < arr.length; i++) {
if (count[arr[i]] < 1) {
count[arr[i]] = count[arr[i]] + 1;
outputArrayLength++;
}
}
for (int i = 1; i < 256; i++) {
count[i] = count[i] + count[i - 1];
}
int[] sortedArray = new int[outputArrayLength];
for (int i = 0; i < arr.length; i++) {
sortedArray[count[arr[i]] - 1] = arr[i];
}
for (int i = 0; i < sortedArray.length; i++) {
System.out.println(sortedArray[i]);
}
}
Reference - discovered this solution while
trying to solve a problem from HackerEarth
If you are a Java programmer, I recommend you to use this.
It will work.
public class DistinctElementsInArray {
//Print all distinct elements in a given array without any duplication
public static void printDistinct(int arr[], int n) {
// Pick all elements one by one
for (int i = 0; i < n; i++) {
// Check if the picked element is already existed
int j;
for (j = 0; j < i; j++)
if (arr[i] == arr[j])
break;
// If not printed earlier, then print it
if (i == j)
System.out.print(arr[i] + " ");
}
}
public static void main(String[] args) {
int array[] = { 4, 5, 9, 5, 4, 6, 6, 5, 4, 10, 6, 4, 5, 3, 8, 4, 8, 3 };
// 4 - 5 5 - 4 9 - 1 6 - 3 10 - 1 3 - 2 8 - 2
int arrayLength = array.length;
printDistinct(array, arrayLength);
}
}
public class DistinctArray {
public static void main(String[] args) {
int num[]={1,2,5,4,1,2,3,5};
for(int i =0;i<num.length;i++)
{
boolean isDistinct=false;
for(int j=0;j<i;j++)
{
if(num[j]==num[i])
{
isDistinct=true;
break;
}
}
if(!isDistinct)
{
System.out.print(num[i]+" ");
}
}
}
}

Categories