Sorry I am still learning programming. Java just stops and seems to be processing something. It says "Building java application Javaapplication2" then just sits there doing nothing. What have a I done to cause this ?
package javaapplication2;
public class JavaApplication2 {
public static void main(String[] args) {
int a [] = {1,2,3};
int c [] = Sortarray.sortlowhigh(a);
int i = 0;
while (i<c.length){
System.out.println("array is" + c[i]);
i++;
}
}
}
package javaapplication2;
public class Sortarray {
public static int[] sortlowhigh(int a[])
{
int i = 0;
int j = 0;
while(j<a.length){
while(i<a.length){
if (a[i]>a[i+1]){
/* store low value in temp*/
int temp = a[i+1];
/* assign low value to be the higher value*/
a[i+1] = a[i];
/* assign the old higher value to be the lower value stored in temp*/
a[i]=temp;
}
j++;
}
}
return a;
}
}
My code is above. A while ago I wrote a sort and remove duplicates method now I want to put them into a class but I am doing something wrong. Please help. Thanks.
I try your code and I can see that you have a infinite loop in the class Sortarray. The variable i is never increased.
Try this code:
public static int[] sortlowhigh(int a[])
{
int i = 0;
int j = 0;
int temp;
while(j< (a.length -1) ){
i = 0;
while(i< (a.length - j - 1)){
if (a[i] > a[i+1]){
/* store low value in temp*/
temp = a[i];
/* assign low value to be the higher value*/
a[i] = a[i+1];
/* assign the old higher value to be the lower value stored in temp*/
a[i+1]=temp;
}
i++;
}
j++;
}
return a;
}
In the sortlowhigh while loop you have i, i < a.lenght is the condition of the second loop and it will continue until i is >= a.length but i never changes it always stay 0.
/*change your code as given*/
public static int[] sortlowhigh(int a[]){
int i = 0;
int j = 0; int temp=0;
while(j<(a.length-1))
{
i=0;
while(i<a.length-j-1)
{
if(a[i]>a[i+1])/* For descending order use < */
{
temp = a[i];
a[i]=a[i+1];
a[i+1] = temp;
}
i++;
}
j++;
}
return a;
}
you should reset the value of i, when the value of j is incremented.
The array is of size 3. but the value of i is already 3. so it gets garbage value in a[i+1].
Hope this helps. I haven't tried the code.
Related
package dsa450;
import java.util.*;
public class countInversion {
public static void main(String[] args) {
Scanner sc=new Scanner(System.in);
System.out.println("Enter the size of Array");
int n=sc.nextInt();
int arr[]=new int[n];
System.out.println("Enter the size of Array");
for(int i=0;i<n;i++){
arr[i]=sc.nextInt();
}
int p=arr.length;
int temp[]=new int[n];
int ans=mergeSort(arr,temp,0,n-1);
System.out.println(ans);
}
static int mergeSort(int[] arr,int[]temp,int l,int r) {
int inv=0;
int mid;
if (l<r) {
mid=(l+r)/2;
inv+= mergeSort(arr,temp,l, mid);
inv+= mergeSort(arr,temp,mid+1,r);
inv+= merge(arr,temp,l,mid+1,r);
}
return inv;
}
private static int merge(int []arr,int []temp,int l,int mid,int r) {
int i=0;
int j=0;
int k=0;
int swap=0;
while(i<=mid-1 && j<=r) {
if(arr[i]<=arr[j]) {
temp[k++]=arr[i++];
}
else {
temp[k++]=arr[j++];
swap+=(mid-i);
}
}
while(i<=mid-1) {
temp[k++]=arr[i++];
}
while(j<=r) {
temp[k++]=arr[j++];
}
for(i=l;i<=r;i++) {
arr[i]=temp[i];
}
return swap;
}
}
enter image description here
this is my code I am trying to solve it for 5 hours but I am not getting what is the problem can anybody help. I check resources also but the code is the same as a source but it is not running.
Hints:
The actual error is that you are attempting to get an array element 1 position beyond the end of the array. (Array indexes go from 0 to array.length - 1.)
Use the line numbers in the stacktrace to work out exactly which line of your code the exception occurs on. It is happening in an array indexing operation in the merge method. There are 6 lines where that could be happening.
Add some trace prints to print out the values of critical variables at key points in the merge method; e.g. what l, r and mid are, and what i, j and k are.
Run the modified code, look at the values output by the trace prints, and try to visualize what the code is doing.
Spot where and why you are going beyond the end of an array ... and figure out what you need to change.
Your merge method is failing because you are not validating k against size of temp array.
I am suggesting below small modifications in your merge method which will give you correct answer:
while (i <= mid - 1 && j <= r && k<temp.length) {
if (arr[i] <= arr[j] ) {
temp[k++] = arr[i++];
} else {
temp[k++] = arr[j++];
swap += (mid - i);
}
}
while (i <= mid - 1 && k < temp.length) {
temp[k++] = arr[i++];
}
while (j <= r && k < temp.length) {
temp[k++] = arr[j++];
}
I need to add List of permutation to ArrayList type but for me when I try to run below code then I am getting same value repeated. Please help me here.
public static void permutation(ArrayList<Integer> perm, ArrayList<ArrayList<Integer>> solution, int index) {
if (index >= perm.size()) {
solution.add(perm);
return;
}
for (int i = index; i < perm.size(); i++) {
Collections.swap(perm, index, i);
permutation(perm, solution, index + 1);
Collections.swap(perm, index, i);
}
}
if passed [1,2,3] as first argument.
Expected output: [[1,2,3],[1,3,2],[2,1,3],[2,3,1],[3,1,2],[3,2,1]] should be added to second argument.
Actual output: [[1,2,3],[1,2,3],[1,2,3],[1,2,3],[1,2,3],[1,2,3]]
You need to understand that
solution.add(perm);
does not add a copy of perm to solution - it only adds a reference to perm. You are changing the contents perm after that line, which means that whatever seems to have been added to solution also changes (because it is the same object).
What you need to do instead is to add a copy of perm to the solution.
In your case the simplest way to create such a copy is by creating a new ArrayList<Integer>(perm):
solution.add(new ArrayList<Integer>(perm));
public class GetAllPermutations {
public static void getPermutations(int[] array){
helper(array, 0);
}
private static void helper(int[] array, int pos){
if(pos >= array.length - 1){
System.out.print("[");
for(int i = 0; i < array.length - 1; i++){
System.out.print(array[i] + ", ");
}
if(array.length > 0)
System.out.print(array[array.length - 1]);
System.out.println("]");
return;
}
for(int i = pos; i < array.length; i++){
int t = array[pos];
array[pos] = array[i];
array[i] = t;
helper(array, pos+1);
t = array[pos];
array[pos] = array[i];
array[i] = t;
}
}
public static void main(String args[]) {
int[] numbers = {1, 2, 3};
getPermutations(numbers);
}
}
I'm trying to make a method than returns the second bigger number of an array.
When I return the value, in console appears 2 or more values. I can't understand why is this happening. Can somebody help me to understand this, please?
I did a method to search the bigger value so I can use it on the one which returns the second bigger.
public class ThirdMax {
public static int maxNum (int[] array) { //Returns the bigger value of the array.
int aux = 0; //Variable to store the bigger value found and compare it with the rest.
for (int i = 0; i < array.length; i++) {
if(array[i] > aux) { //If the actual value is bigger than the aux
aux = array[i]; //override the aux value with actual value.
}
}
System.out.println(aux);
return aux;
}
public static int secondMax(int[] array) { //Returns the second bigger value on the array.
int valorMax = maxNum(array); //Store the bigger value on a variable so we can use it later.
int valorMax2 = 0; //Variable to store the result.
int[] auxArray = new int [array.length];
for (int i = 0; i < array.length; i++) {
if(array[i] == valorMax) { //When we get to the valorMax, we replace it in the array with a 0.
array[i] = 0;
} else {
auxArray[i] = array[i];
}
valorMax2 = maxNum(auxArray); //Search again the bigger value after the previous one is replaced by 0.
}
return valorMax2;
}
}
Thanks in advance for your time!
You call maxNum(auxArray); multiple times. Each of them prints a max value.
Hence you received multiple result.
To immediately resolve it, remove the print System.out.println(aux);
in your function.
And make only one print function right before you return
System.out.println(valorMax2);
return valorMax2;
But your code looks not good. It need multiple improvement.
To find the second biggest number, you only need to loop once like this:
public static int secondMax(int[] array) {
int max = Integer.MIN_VALUE; // Max value
int secondMax = Integer.MIN_VALUE; // Second max value, its our result
for (int i = 0; i < array.length; i++) {
if (array[i] > max) {
secondMax = max;
max = array[i];
} else if (array[i] > secondMax) {
secondMax = array[i];
}
}
return secondMax;
}
This looks OK, but can't extends to find n-th max number, because our if conditions will be very complex. Then you try to find max number once at a time:
// Return max number in array which is lower than ceilValue
// Return Integer.MIN_VALUE if no such value found
public static int maxValueBelow(int[] array, int ceilValue) {
int max = Integer.MIN_VALUE;
for (int i = 0; i<array.length; i++) {
if (array[i] < ceilValue && array[i] > max) {
max = array[i];
}
}
return max;
}
public static int findNthValue(int[] array) {
int maxValue = maxValueBelow(array, Integer.MAX_VALUE);
int secondMaxValue = maxValueBelow(array, maxValue);
int thirdMaxValue = maxValueBelow(array, secondMaxValue);
// You can improve this function by give it's a second parameter `n`, and use for loop to find the `n-th` max value.
}
Since you're setting the largest number to 0 you really don't need auxArray.
You also don't need a second valorMax.
You might want to refactor your code to the following.
public static int secondMax(int[] array) {
int valorMax = maxNum(array);
for (int i = 0; i < array.length; i++) {
if(array[i] == valorMax) {
array[i] = 0;
}
}
return maxNum(array); // just return the result of maxNum(array)
}
be sure to remove the print statement from maxNum if you don't want your program to print 2 numbers to console.
Because you put get second max function in the wrong place.
public static int secondMax(int[] array) {
int valorMax = maxNum(array);
int valorMax2 = 0;
int[] auxArray = new int [array.length];
for (int i = 0; i < array.length; i++) {
if(array[i] == valorMax) {
array[i] = 0;
} else {
auxArray[i] = array[i];
}
}
valorMax2 = maxNum(auxArray); // this should be out of loop
return valorMax2;
}
}
I am stuck in the following program:
I have an input integer array which has only one non duplicate number, say {1,1,3,2,3}. The output should show the non duplicate element i.e. 2.
So far I did the following:
public class Solution {
public int singleNumber(int[] arr){
int size = arr.length;
int temp = 0;
int result = 0;
boolean flag = true;
int[] arr1 = new int[size];
for(int i=0;i<size;i++){
temp = arr[i];
for(int j=0;j<size;j++){
if(temp == arr[j]){
if(i != j)
//System.out.println("Match found for "+temp);
flag = false;
break;
}
}
}
return result;
}
public static void main(String[] args) {
int[] a = {1,1,3,2,3};
Solution sol = new Solution();
System.out.println("SINGLE NUMBER : "+sol.singleNumber(a));
}
}
Restricting the solution in array is preferable. Avoid using collections,maps.
public class NonRepeatingElement {
public static void main(String[] args) {
int result =0;
int []arr={3,4,5,3,4,5,6};
for(int i:arr)
{
result ^=i;
}
System.out.println("Result is "+result);
}
}
Since this is almost certainly a learning exercise, and because you are very close to completing it right, here are the things that you need to change to make it work:
Move the declaration of flag inside the outer loop - the flag needs to be set to true every iteration of the outer loop, and it is not used anywhere outside the outer loop.
Check the flag when the inner loop completes - if the flag remains true, you have found a unique number; return it.
From Above here is the none duplicated example in Apple swift 2.0
func noneDuplicated(){
let arr = [1,4,3,7,3]
let size = arr.count
var temp = 0
for i in 0..<size{
var flag = true
temp = arr[i]
for j in 0..<size{
if(temp == arr[j]){
if(i != j){
flag = false
break
}
}
}
if(flag == true){
print(temp + " ,")
}
}
}
// output : 1 , 4 ,7
// this will print each none duplicated
/// for duplicate array
static void duplicateItem(int[] a){
/*
You can sort the array before you compare
*/
int temp =0;
for(int i=0; i<a.length;i++){
for(int j=0; j<a.length;j++){
if(a[i]<a[j]){
temp = a[i];
a[i] = a[j];
a[j] = temp;
}
}
}
int count=0;
for(int j=0;j<a.length;j++) {
for(int k =j+1;k<a.length;k++) {
if(a[j] == a[k]) {
count++;
}
}
if(count==1){
System.out.println(a[j]);
}
count = 0;
}
}
/*
for array of non duplicate elements in array just change int k=j+1; to int k = 0; in for loop
*/
static void NonDuplicateItem(int[] a){
/*
You can sort the array before you compare
*/
int temp =0;
for(int i=0; i<a.length;i++){
for(int j=0; j<a.length;j++){
if(a[i]<a[j]){
temp = a[i];
a[i] = a[j];
a[j] = temp;
}
}
}
int count=0;
for(int j=0;j<a.length;j++) {
for(int k =0 ;k<a.length;k++) {
if(a[j] == a[k]) {
count++;
}
}
if(count==1){
System.out.println(a[j]);
}
count = 0;
}
}
public class DuplicateItem {
public static void main (String []args){
int[] a = {1,1,1,2,2,3,6,5,3,6,7,8};
duplicateItem(a);
NonDuplicateItem(a);
}
/// for first non repeating element in array ///
static void FirstNonDuplicateItem(int[] a){
/*
You can sort the array before you compare
*/
int temp =0;
for(int i=0; i<a.length;i++){
for(int j=0; j<a.length;j++){
if(a[i]<a[j]){
temp = a[i];
a[i] = a[j];
a[j] = temp;
}
}
}
int count=0;
for(int j=0;j<a.length;j++) {
//int k;
for(int k =0; k<a.length;k++) {
if(a[j] == a[k]) {
count++;
}
}
if(count==1){
System.out.println(a[j]);
break;
}
count = 0;
}
}
public class NonDuplicateItem {
public static void main (String []args){
int[] a = {1,1,1,2,2,3,6,5,3,6,7,8};
FirstNonDuplicateItem(a);
}
I have a unique answer, it basically takes the current number that you have in the outer for loop for the array and times it by itself (basically the number to the power of 2). Then it goes through and every time it sees the number isn't equal to double itself test if its at the end of the array for the inner for loop, it is then a unique number, where as if it ever find a number equal to itself it then skips to the end of the inner for loop since we already know after one the number is not unique.
public class Solution {
public int singleNumber(int[] arr){
int size = arr.length;
int temp = 0;
int result = 0;
int temp2 = 0;
int temp3 = 0;
boolean flag = true;
int[] arr1 = new int[size];
for(int i=0;i<size;i++){
temp = arr[i];
temp2 = temp*temp;
for(int j=0;j<size;j++){
temp3 = temp*arr[j];
if(temp2==temp3 && i!=j)
j=arr.length
if(temp2 != temp3 && j==arr.length){
//System.out.println("Match found for "+temp);
flag = false;
result = temp;
break;
}
}
}
return result;
}
public static void main(String[] args) {
int[] a = {1,1,3,2,3};
Solution sol = new Solution();
System.out.println("SINGLE NUMBER : "+sol.singleNumber(a));
}
}
not tested but should work
public class Solution {
public int singleNumber(int[] arr){
int size = arr.length;
int temp = 0;
int result = 0;
boolean flag = true;
int[] arr1 = new int[size];
for(int i=0;i<size;i++){
temp = arr[i];
int count=0;
for(int j=0;j<size;j++){
if(temp == arr[j]){
count++;
}
}
if (count==1){
result=temp;
break;
}
}
return result;
}
Try:
public class Answer{
public static void main(String[] args) {
int[] a = {1,1,3,2,3};
int[] b =new int[a.length];
//instead of a.length initialize it to maximum element value in a; to avoid
//ArrayIndexOutOfBoundsException
for(int i=0;i<a.length;i++){
int x=a[i];
b[x]++;
}
for(int i=0;i<b.length;i++){
if(b[i]==1){
System.out.println(i); // outputs 2
break;
}
}
}
}
PS: I'm really new to java i usually code in C.
Thanks #dasblinkenlight...followed your method
public class Solution {
public int singleNumber(int[] arr){
int size = arr.length;
int temp = 0;
int result = 0;
int[] arr1 = new int[size];
for(int i=0;i<size;i++){
boolean flag = true;
temp = arr[i];
for(int j=0;j<size;j++){
if(temp == arr[j]){
if(i != j){
// System.out.println("Match found for "+temp);
flag = false;
break;
}
}
}
if(flag == true)
result = temp;
}
return result;
}
public static void main(String[] args) {
int[] a = {1,1,3,2,3};
Solution sol = new Solution();
System.out.println("SINGLE NUMBER : "+sol.singleNumber(a));
}
}
One disastrous mistake was not enclosing the content of if(i != j) inside braces. Thanks all for your answers.
If you are coding for learning then you can solve it with still more efficiently.
Sort the given array using merge sort of Quick Sort.
Running time will be nlogn.
The idea is to use Binary Search.
Till required element found All elements have first occurrence at even index (0, 2, ..) and next occurrence at odd index (1, 3, …).
After the required element have first occurrence at odd index and next occurrence at even index.
Using above observation you can solve :
a) Find the middle index, say ‘mid’.
b) If ‘mid’ is even, then compare arr[mid] and arr[mid + 1]. If both are same, then the required element after ‘mid’ else before mid.
c) If ‘mid’ is odd, then compare arr[mid] and arr[mid – 1]. If both are same, then the required element after ‘mid’ else before mid.
Another simple way to do so..
public static void main(String[] art) {
int a[] = { 11, 2, 3, 1,1, 6, 2, 5, 8, 3, 2, 11, 8, 4, 6 ,5};
Arrays.sort(a);
System.out.println(Arrays.toString(a));
for (int j = 0; j < a.length; j++) {
if(j==0) {
if(a[j]!=a[j+1]) {
System.out.println("The unique number is :"+a[j]);
}
}else
if(j==a.length-1) {
if(a[j]!=a[j-1]) {
System.out.println("The unique number is :"+a[j]);
}
}else
if(a[j]!=a[j+1] && a[j]!=a[j-1]) {
System.out.println("The unique number is :"+a[j]);
}
}
}
Happy Coding..
Using multiple loops the time complexity is O(n^2), So the effective way to resolve this using HashMap which in the time complexity of O(n). Please find my answer below,
`public static int nonRepeatedNumber(int[] A) {
Map<Integer, Integer> countMap = new HashMap<>();
int result = -1;
for (int i : A) {
if (!countMap.containsKey(i)) {
countMap.put(i, 1);
} else {
countMap.put(i, countMap.get(i) + 1);
}
}
Optional<Entry<Integer, Integer>> optionalEntry = countMap.entrySet().stream()
.filter(e -> e.getValue() == 1).findFirst();
return optionalEntry.isPresent() ? optionalEntry.get().getKey() : -1;
}
}`
I was solving the problem on hackerrank. I had two approaches in my mind :
input : unsorted array(a) and k
First Approach :
1) Sort the array
2) for each array element a[i] ,find the element a[i]+K using binary search.If found increament the count and break the inner loop.
Second Approach :
1) Sort the array
2) for each array element a[i] ,find the element a[i]+K using linearsearch.If found increament the count and break the inner loop.
I found the First approach to be better as it will solve the problem in n(logn). But when multiple test cases are on the solutions the approach 2 takes lesser time . Can some one please explain why ?
Below are the code for the two approaches :
First Approach Code :
static int pairs(int[] a,int k) {
/* Complete this function */
int temp;
int len=a.length;
int count=0;
int beg;
int mid;
int end;
int midVal;
Arrays.sort(a);
for(int i=0;i<len-1;i++){
temp=a[i]+k;
beg=i+1;
end=len-1;
for(int l=beg;l<len;l++){
mid=(beg+end)/2;
midVal=a[mid];
if(midVal==temp){
count++;
break;
}
else if(midVal>temp){
end=mid-1;
}
else{
beg=mid+1;
}
}
}
return count;
}
Second Approach Code :
static int pairs(int[] a,int k) {
/* Complete this function */
int temp;
int len=a.length;
int count=0;
Arrays.sort(a);
for(int i=0;i<len;i++){
temp=a[i];
for(int j=i+1;j<len;j++){
if(temp-a[j]==-k){
count++;
break;
}
}
}
return count;
}
The first approach is the best here among the two but there is better approach than both:-
Here a pseudo code for a better approach:-
for(i=0;i<Arr.length;i++) {
Hashmap.add(Arr[i])
}
count=0;
for(j=0;j<Arr.length;j++) {
if(Hashmap.containsKey(Arr[j]+k))
count++;
}
Time complexity: O(N)
whereas your approach = O(NlogN)
Edit:-
Note:- My approach has extra space complexity of O(N) for Hash table whereas suggested approach is inplace.
In your 1st code, your inner loop termination condition is incorrect. It should terminate if the beg and end pointers cross each other.
Change it to while (beg <= end) or for (; beg <= end; )
Also, for the second approach there is no need for sorting the array.
You can also use set no need to use hashmap
public static void main(String[] args) throws Exception {
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
int[] firstLine = Stream.of(in.readLine().split(" ")).mapToInt(Integer::parseInt).toArray();
int count = firstLine[0];
int diff = firstLine[1];
Set<Integer> numbers = new HashSet<Integer>(Stream.of(in.readLine().split(" ")).map(Integer::valueOf).collect(Collectors.toList()));
int pairCount = 0;
for (Integer number : numbers) {
pairCount += (numbers.contains(number+diff) ? 1:0);
}
System.out.println(pairCount);
}
private static int CountDistinctPairs(int[] nums, int k) {
// TODO Auto-generated method stub
HashMap<Integer, Boolean> map = new HashMap<Integer, Boolean>();
HashSet<String> set = new HashSet<String>();
for(int i =0;i < nums.length;i++){
map.put(nums[i],true);
}
for (int i = 0 ; i < nums.length; i++){
if(map.containsKey(nums[i]+k)){
String a = "";
if(nums[i]<nums[i]+k){
a = "("+nums[i]+","+(nums[i]+k)+")";
}
else{
a = "("+(nums[i] + k)+","+nums[i]+")";
}
set.add(a);
}
}
System.out.println(set);
return set.size();
}
My solution
System.out.println("findPair:"+findPair(new int[]{4,7,1,2,5,3,0,7,8,5,2}, 3));
public static int findPair(int[] nums, int target){
Arrays.sort(nums);
int count = 0;
String pairText = "";
for(int i =0; i < nums.length;i++){
for(int j =i+1; j < nums.length;j++){
if(nums[j]-nums[i] == target && (!pairText.equals(nums[i]+", "+nums[j]))){
//System.out.println(nums[i]+", "+nums[j]);
pairText = nums[i]+", "+nums[j];
count++;
}
}
}
return count;
}
static boolean checkDuplicatesWithinK(int arr[], int k)
{
// Creates an empty hashset
HashSet<Integer> set = new HashSet<>();
// Traverse the input array
for (int i=0; i<arr.length; i++)
{
// If already present n hash, then we found
// a duplicate within k distance
if (set.contains(arr[i]))
return true;
// Add this item to hashset
set.add(arr[i]);
// Remove the k+1 distant item
if (i >= k)
set.remove(arr[i-k]);
}
return false;
}
public static void main (String[] args)
{
int arr[] = {10, 5, 3, 4, 3, 5, 6};
if (checkDuplicatesWithinK(arr, 3))
System.out.println("Yes");
else
System.out.println("No");
}