Getting output of 0 each time when im ment to get 3 looked over my code my not sure where i have gone wrong i can do it without using a method i know but just trying to practice java
public class App {
public static int second(int a[],int n) {
int[] arr = new int [n];
int temp;
for(int i=0;i<n;i++) {
for(int j=i+1;j<n;j++) {
if(arr[i] > arr[j]) {
temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
}
}
return arr[n-2];
}
public static void main(String[] args) {
int[] arr = {1,3,2,5,3};
int n = 5;
int result = second(arr,n);
System.out.println(result);
}
}
You could change the array parameter name arr and remove the declaration or copy the values from a to arr.
public static int second(int arr[],int n) {
int temp;
for(int i=0;i<n;i++) {
for(int j=i+1;j<n;j++) {
if(arr[i] > arr[j]) {
temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
}
}
return arr[n-2];
}
The reason you get zero is because the primitive int cannot be null. So, when you create the array of length 5, it starts out filled with zeroes.
Doing it by using streams:
public static int second(int a[]) {
return Arrays.stream(a)
.sorted()
.skip(a.length - 2)
.findFirst()
.getAsInt();
}
I removed the second argument. It sorts your array and skips all the elements prior to the one you want, before picking the now first element.
public static int second(int[] arr) {
int highest = arr[0];
int second = 0;
for (int i = 1; i < arr.length; i++) {
int j = arr[i];
if (j >= highest) {
highest = j;
} else if (j > second) {
second = j;
}
}
return second;
}
public static void main(String[] args) {
int[] arr = {1, 3, 2, 5, 3};
int result = second(arr);
System.out.println(result);
}
Here is one way that doesn't require sorting.
int[] arr = { 10, 2, 3, 19, 2, 3, 5 };
System.out.println(second(arr));
prints
10
set largest to the first value in the array
set secondLargest to the smallest possible
now iterate thru the array.
if the current value is greater than largest:
replace secondLargest with Largest
replace largest with current value
else check to see if current value is greater than secondLargest and assign if true.
public static int second(int arr[]) {
int largest = arr[0];
int secondLargest = Integer.MIN_VALUE;
for (int i = 1; i < arr.length; i++) {
if (arr[i] > largest) {
secondLargest = largest;
largest = arr[i];
} else if (arr[i] > secondLargest) {
secondLargest = arr[i];
}
}
return secondLargest;
}
public static int second(int arr[],int n) {
int temp;
if(arr.length < 2) {
return -1;
}
else {
for(int i=0;i<n;i++) {
for(int j=i+1;j<n;j++) {
if(arr[i] > arr[j]) {
temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
}
}
return arr[n-2];
}
public static void main(String[] args) {
// TODO Auto-generated method stub
int a[] = {23,14,56,77,66,67};
int high = 0;
int sec = 0;
for(int i = 0 ; i <a.length; i++){
if(high < a[i]){
sec = high;
high = a[i];
}
else if(sec < a[i]){
sec = a[i];
}
}
System.out.println("the first highest number is " + high);
System.out.println("the second highest number is " + sec);
}
}
public static int sec(){
int arr[] = {12,3,67,4,5,65};
int high = 0;
int low = 0;
for(int i = 0 ; i < arr.length ; i ++){
if(high < arr[i]){
low = high;
high = arr[i];
}
else if(low < arr[i]){
low = arr[i];
}
}
return low;
}
public static void main(String[] args) {
// TODO Auto-generated method stub
sch obj = new sch();
int a = obj.sec();
System.out.println(a);
}
}
package com;
public class FindSecondHighestNumberInArray {
public static void main(String[] args) {
int []arrayOfIngeger = {-23,-989,-878,-2,-5,-3,-4,-123,-345,-98,-675,-98};
int highestNumber = arrayOfIngeger[0];
int secHighestNumber = 0;
for(int i = 1; i < arrayOfIngeger.length; i++ ) {
if(highestNumber < arrayOfIngeger[i]) {
secHighestNumber = highestNumber;
highestNumber = arrayOfIngeger[i];
}else if(secHighestNumber < arrayOfIngeger[i] && arrayOfIngeger[i] != highestNumber) {
secHighestNumber = arrayOfIngeger[i];
}
}
System.out.println("second Highest Number in Array : "+secHighestNumber);
}
}
Related
public class MaxSumSubArray
{
public int findSum (int[] arr)
{
int maxSum;
//This covers when we have just one element
if(arr.length == 1) {
maxSum = arr[0];
} else {
maxSum = Integer.MIN_VALUE;
for (int i = 0; i < arr.length; i++) {
int sum = arr[i]; // -1
for (int j = i + 1; j < arr.length; j++) {
// This is the case when your new elem is greater than the sum of prev elements
if(arr[j] > sum + arr[j]) {
sum = arr[j];
} else {
sum = sum + arr[j];
}
if (sum > maxSum) {
maxSum = sum;
}
}
}
}
return maxSum;
}
public static void main(String[] args) {
int[] arr = {-2,1,-3,4,-1,2,1,-5,4};
MaxSumSubArray subArray = new MaxSumSubArray();
System.out.println("MAx sum is:"+ subArray.findSum(arr));
}
}
I have written this code for maximum Sum subarray, I am using brute force approach.
Input: nums = [-2,1,-3,4,-1,2,1,-5,4]
Output: 6
Explanation: [4,-1,2,1] has the largest sum = 6.
This code is working for almost every set of input except one [-1,-2]. Can somebody help which I am missing here. Thanks
You should not reinitialize the sum variable in the second loop, you should choose the largest value after each add arr[j] to sum.
public int findSum (int[] arr)
{
int maxSum;
//This covers when we have just one element
if(arr.length == 1) {
maxSum = arr[0];
} else {
maxSum = Integer.MIN_VALUE;
for (int i = 0; i < arr.length; i++) {
int sum = arr[i]; // -1
if (sum > maxSum) {
maxSum = sum;
}
for (int j = i + 1; j < arr.length; j++) {
sum = sum + arr[j];
if (sum > maxSum) {
maxSum = sum;
}
}
}
}
return maxSum;
}
I am trying to get an output of [4,6,6,7] with length 4 where arr[i] <= arr[i+1] where it is non-decreasing and it is contiguous. I know what i have to do but i dont know how to do it. my code prints out [3,4,6,6,7]. I am just having trouble on the contiguous part, any help? im not allowed to use extra arrays.
public static void ascentLength(int arr[], int size) {
int length = 0;
int index = 0;
int count = 1;
for (int i = 0; i < size-1; i++) {
index = i;
if (arr[0] <= arr[i+1] && count >0) {
System.out.println(arr[i]+ " index:" + index);
length++;
count++;
}
if (arr[0] >= arr[i+1]) {
}
}
System.out.println("length: " + length);
}
/* Driver program to test above function */
public static void main(String[] args) {
int arr[] = {5, 3, 6, 4, 6, 6, 7, 5};
int n = arr.length;
ascentLength(arr, n);
}
Here is my solution, it would be easier, if you could work with List, but this works for arrays:
public static void ascentLength(int arr[], int size) {
if(size == 1) System.out.println("length: 1");
// variables keeping longest values
int longestStartingIndex = 0;
int longestLength = 1;
// variables keeping current values
int currentStartingIndex = 0;
int currentCount = 1;
for (int i = 1; i < size; i++) {
if (arr[i-1] <= arr[i]) {
currentCount++;
} else {
// check if current count is the longest
if(currentCount > longestLength) {
longestLength = currentCount;
longestStartingIndex = currentStartingIndex;
}
currentStartingIndex = i;
currentCount = 1;
}
}
if(currentCount > longestLength) {
longestLength = currentCount;
longestStartingIndex = currentStartingIndex;
}
}
I'm trying to execute this so that it prints out the longest sequence of the same number. The error I get is that it's telling me that a class or enum is expected. Here's my code:
public class D4 {
private static int getLongestRun(int[] array) {
int count = 1;
int max = 1;
for (int i = 1; i < array.length; i++) {
if (array[i] == array[i - 1]) {
count++;
}
else {
count = 1;
}
if (count > max) {
max = count;
}
}
}
public static void main(String[] args) {
int[] array = new int[]{5, 6, 6, 45, 2, 2, 2};
System.out.println(getLongestRun(array));
}
}
This belongs as a comment, but I will give you full code so that it is clear. Just return max at the end of your getLongestRun() method:
private static int getLongestRun(int[] array) {
int count = 1;
int max = 1;
for (int i = 1; i < array.length; i++) {
if (array[i] == array[i - 1]) {
count++;
}
else {
count = 1;
}
if (count > max) {
max = count;
}
}
// you forgot to return the length of the longest sequence to the caller
return max;
}
function getLongestRun() is missing return max; statement.
I am writing a JAVA code to generate all permutations of a integer array.
Though I am getting the number of permutations right, the permutations themselves are not correct.
On running I obtain:
Input array Length
3
1
2
3
0Permutation is
1, 2, 3,
##########################
1Permutation is
1, 3, 2,
##########################
2Permutation is
3, 1, 2,
##########################
3Permutation is
3, 2, 1,
##########################
4Permutation is
1, 2, 3,
##########################
5Permutation is
1, 3, 2,
##########################
6 number of permutations obtained
BUILD SUCCESSFUL (total time: 3 seconds)
public class PermulteArray {
public static int counter = 0;
public static void Permute(int[] input, int startindex) {
int size = input.length;
if (size == startindex + 1) {
System.out.println(counter + "Permutation is");
for (int i = 0; i < size; i++) {
System.out.print(input[i] + ", ");
}
System.out.println();
System.out.println("##########################");
counter++;
} else {
for (int i = startindex; i < size; i++) {
int temp = input[i];
input[i] = input[startindex];
input[startindex] = temp;
Permute(input, startindex + 1);
}
}
}
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.println("Input array Length");
int arraylength = in.nextInt();
int[] input = new int[arraylength];
for (int i = 0; i < arraylength; i++) {
input[i] = in.nextInt();
}
counter = 0;
Permute(input, 0);
System.out.println(counter + " number of permutations obtained");
}
}
int temp=input[i];
input[i]=input[startindex];
input[startindex]=temp;
Permute(input, startindex+1);
You've swapped an element before calling Permute but you need to swap it back again afterwards to keep consistent positions of elements across iterations of the for-loop.
This is the best solution I have seen so far :
public static void main(String[] args) {
int[] a = { 1, 2, 3, 4, 5, 6 };
permute(0, a);
}
public static void permute(int start, int[] input) {
if (start == input.length) {
//System.out.println(input);
for (int x : input) {
System.out.print(x);
}
System.out.println("");
return;
}
for (int i = start; i < input.length; i++) {
// swapping
int temp = input[i];
input[i] = input[start];
input[start] = temp;
// swap(input[i], input[start]);
permute(start + 1, input);
// swap(input[i],input[start]);
int temp2 = input[i];
input[i] = input[start];
input[start] = temp2;
}
}
check this out
for (int i = startindex; i < input2.length; i++) {
char[] input = input2.clone();
char temp = input[i];
input[i] = input[startindex];
input[startindex] = temp;
permute(input, startindex + 1);
}
//This will give correct output
import java.util.Scanner;
public class PermulteArray {
public static int counter = 0;
public static void Permute(int[] input, int startindex) {
int size = input.length;
if (size == startindex + 1) {
System.out.println(counter + "Permutation is");
for (int i = 0; i < size; i++) {
System.out.print(input[i] + ", ");
}
System.out.println();
System.out.println("##########################");
counter++;
} else {
for (int i = startindex; i < size; i++) {
int temp = input[i];
input[i] = input[startindex];
input[startindex] = temp;
Permute(input, startindex + 1);
temp = input[i];
input[i] = input[startindex];
input[startindex] = temp;
}
}
}
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.println("Input array Length");
int arraylength = in.nextInt();
int[] input = new int[arraylength];
for (int i = 0; i < arraylength; i++) {
input[i] = in.nextInt();
}
counter = 0;
Permute(input, 0);
System.out.println(counter + " number of permutations obtained");
}
}
You can solve this using recursive calls.
https://github.com/Pratiyush/Master/blob/master/Algorithm%20Tutorial/src/arrays/Permutations.java
public void swap(int[] arr, int i, int j)
{
int tmp = arr[i];
arr[i] = arr[j];
arr[j] = tmp;
}
public void permute(int[] arr, int i)
{
if (i == arr.length)
{
System.out.println(Arrays.toString(arr));
return;
}
for (int j = i; j < arr.length; j++)
{
swap(arr, i, j);
permute(arr, i + 1); // recurse call
swap(arr, i, j); // backtracking
}
}
public static void main(String[] args) {
Permutations permutations = new Permutations();
int[] arr = {1, 2, 3,4};
permutations.permute(arr, 0);
}
Also, other approaches are available in
http://www.programcreek.com/2013/02/leetcode-permutations-java/
http://www.programcreek.com/2013/02/leetcode-permutations-ii-java/
public class PermuteArray {
public static void permute(char[] input2, int startindex) {
if (input2.length == startindex) {
displayArray(input2);
} else {
for (int i = startindex; i < input2.length; i++) {
char[] input = input2.clone();
char temp = input[i];
input[i] = input[startindex];
input[startindex] = temp;
permute(input, startindex + 1);
}
}
}
private static void displayArray(char[] input) {
for (int i = 0; i < input.length; i++) {
System.out.print(input[i] + "; ");
}
System.out.println();
}
public static void main(String[] args) {
char[] input = { 'a', 'b', 'c', 'd'};
permute(input, 0);
}
}
import java.util.ArrayList;
public class RecursivePermGen {
void permGen(int n, int m, ArrayList<Integer> cur) {
if(m == 0) {
System.out.println(cur);
return;
}
for(int i = 1; i <= n; i++) {
cur.add(0, i);
permGen(n, m-1, cur);
cur.remove(0);
}
}
public static void main(String[] args) {
RecursivePermGen pg = new RecursivePermGen();
ArrayList<Integer> cur = new ArrayList<Integer>();
pg.permGen(2, 2, cur);
}
}
I have simple answer for this question, you can try with this.
public class PermutationOfString {
public static void main(String[] args) {
permutation("123");
}
private static void permutation(String string) {
printPermutation(string, "");
}
private static void printPermutation(String string, String permutation) {
if (string.length() == 0) {
System.out.println(permutation);
return;
}
for (int i = 0; i < string.length(); i++) {
char toAppendToPermutation = string.charAt(i);
String remaining = string.substring(0, i) + string.substring(i + 1);
printPermutation(remaining, permutation + toAppendToPermutation);
}
}
}
A solution i have used several times (mostly for testing purposes) is in the following gist. It is based on the well-known algorithm to generate permutations in lexicographic order (no recursion):
/**
* Compute next (in lexicographic order) permutation and advance to it.
*
* Find greater index i for which a j exists, such that:
* j > i and a[i] < a[j] (i.e. the 1st non-inversion).
* For those j satisfying the above, we pick the greatest.
* The next permutation is provided by swapping
* items at i,j and reversing the range a[i+1..n]
*/
void advanceToNext() {
// The array `current` is the permutation we start from
// Find i when 1st non-inversion happens
int i = n - 2;
while (i >= 0 && current[i] >= current[i + 1])
--i;
if (i < 0) {
// No next permutation exists (current is fully reversed)
current = null;
return;
}
// Find greater j for given i for 1st non-inversion
int j = n - 1;
while (current[j] <= current[i])
--j;
// Note: The range a[i+1..n] (after swap) is reverse sorted
swap(current, i, j); // swap current[i] <-> current[j]
reverse(current, i + 1, n); // reverse range [i+1..n]
}
A complete solution (in the form of a class) lies here:
https://gist.github.com/drmalex07/345339117fef6ca47ca97add4175011f
Hi all I want to find out second Largest no in Array accept negative numbers. I have used following code and this display second largest no of only positive no.So please suggest me how to do this.
class ArrayExample {
public static void main(String[] args) {
int secondlargest = 0;
int largest = 0;
Scanner input = new Scanner(System.in);
System.out.println("Enter array values: ");
int arr[] = new int[5];
for (int i = 0; i < arr.length; i++) {
arr[i] = input.nextInt();
if (largest < arr[i]) {
secondlargest = largest;
largest = arr[i];
}
if (secondlargest < arr[i] && largest != arr[i])
secondlargest = arr[i];
}
System.out.println("Second Largest number is: " + secondlargest);
}
}
The problem comes from the fact that you initialize your two variables to 0 in the lines:
int secondlargest = 0;
int largest = 0;
You should instead initialize them to Integer.MIN_VALUE and then it will also work for negative values.
Initialize the variables secondlargest and largest with the smallest negative values.
Use this code:
class ArrayExample {
public static void main(String[] args) {
int secondlargest = Integer.MIN_VALUE;
int largest = Integer.MIN_VALUE;
Scanner input = new Scanner(System.in);
System.out.println("Enter array values: ");
int arr[] = new int[5];
for (int i = 0; i < arr.length; i++) {
arr[i] = input.nextInt();
if (largest < arr[i]) {
secondlargest = largest;
largest = arr[i];
}
if (secondlargest < arr[i] && largest != arr[i])
secondlargest = arr[i];
}
System.out.println("Second Largest number is: " + secondlargest);
}
}
Initialize largest and secondLargest to Integer.MIN_VALUE instead of zero.
This works for me, for both positive and negative values. Before the loop, you need to initialize the largest and secondlargest variables with very small values, by doing this you can be (almost) sure that all the other values in the array will be greater than them:
int largest = Integer.MIN_VALUE;
int secondlargest = Integer.MIN_VALUE;
Inside the loop:
if (arr[i] > largest) {
secondlargest = largest;
largest = arr[i];
}
else if (arr[i] != largest && arr[i] > secondlargest) {
secondlargest = arr[i];
}
After the loop:
if (secondlargest != Integer.MIN_VALUE)
System.out.println("Second Largest number is: " + secondlargest);
Notice that the last check is required for the (rather unlikely) case where all the elements in the array happen to be Integer.MIN_VALUE.
package com.demo.mum;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
/**
* #author cyruses
*
*/
public class SecondLargest {
public static int largest = Integer.MIN_VALUE;
public static int secondLargest = Integer.MIN_VALUE;
public static void main(String args[]) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
System.out.println("Enter the Size of Array:");
int n = Integer.parseInt(br.readLine());
int a[] = new int[n];
System.out.println("Enter the elements on array:");
for (int i = 0; i < a.length; i++) {
a[i] = Integer.parseInt(br.readLine());
}
System.out.println("Elements you entered are:");
for (int i = 0; i < a.length; i++) {
System.out.println("a[" + i + "]" + "=" + a[i]);
}
if (a.length <= 2) {
if (a[0] == a[1]) {
System.out.println("Theres no second largest number in your array");
} else {
System.out.println("SecondLargest:" + secondLargest(a));
}
} else {
System.out.println("SecondLargest:" + secondLargest(a));
}
}
private static int secondLargest(int[] a) {
for (int i = 0; i < a.length; i++) {
if (a[i] > largest) {
secondLargest = largest;
largest = a[i];
} else if (a[i] > secondLargest) {
secondLargest = a[i];
}
}
return secondLargest;
}
}
I think this method may be useful it takes around n+log(n)-2 comparisons
import java.util.ArrayList;
public class SecondLargest {
static ArrayList<ArrayList<Integer>> level = new ArrayList<ArrayList<Integer>>();
public static void main(String[] args) {
int input[]={9,8,7,4,5,6,1,2,3,1,1,21,33,32,1,2,3,12,3,2,1};
ArrayList<Integer> arr= new ArrayList<Integer>();
for(int i=0;i<input.length;i++){
arr.add(input[i]);
}
level.add(arr);
seconLarger(arr);
System.out.println(SecondLarge(level));
}
private static ArrayList<Integer> seconLarger(ArrayList<Integer> arr) {
ArrayList<Integer> tmp= new ArrayList<Integer>();
if (arr.size()==1)
{
return arr;
}
if(arr.size()%2==0)
{
for(int i=0;i<arr.size();i=i+2)
{
if(arr.get(i)>arr.get(i+1))
{
tmp.add(arr.get(i));
}
else
{
tmp.add(arr.get(i+1));
}
}
}
else
{
for(int i=0;i<arr.size()-1;i=i+2)
{
if(arr.get(i)>arr.get(i+1))
{
tmp.add(arr.get(i));
}
else
{
tmp.add(arr.get(i+1));
}
}
tmp.add(arr.get(arr.size()-1));
}
level.add(tmp);
return seconLarger(tmp);
}
private static int SecondLarge(ArrayList<ArrayList<Integer>> li)
{
int li_size=li.size();
int large=li.get(li_size-1).get(0);
int secondlarge=0;
int tmp=0;
for(int i=li_size-2;i>=0;i--)
{
ArrayList<Integer> arr = li.get(i);
if(large==arr.get(tmp))
{
if(tmp+1<arr.size())
{
if(secondlarge<arr.get(tmp+1))
{
secondlarge=arr.get(tmp+1);
}
}
}
else
{
if(secondlarge<arr.get(tmp))
{
secondlarge=arr.get(tmp);
}
tmp=tmp+1;
}
tmp=tmp*2;
}
return secondlarge;
}}
Or here is a gimmicky Java implementation which doesn't rely on Integer.MIN_VALUE
int findSecondHighest(int[] arr){
if(arr == null || arr.length < 2){
throw new IllegalArgumentException();
}
int fh,sh;
if(arr[0]>=arr[1]){
fh = arr[0];
sh = arr[1];
}else{
fh = arr[1];
sh = arr[0];
}
for (int i = 2; i < arr.length; i++) {
if(fh < arr[i]){
sh = fh;
fh = arr[i];
}else if(sh < arr[i]){
sh = arr[i];
}
}
return sh;
}
Instead of initializing the second largest number to min value or zero. You can follow below code to get second largest number.
import java.util.Scanner;
public class SecondLargestNumber {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int[] a;
int n;
System.out.println("Enter number of elements");
n = scanner.nextInt();
a = new int[n];
for(int i=0; i<n; i++) {
a[i] = scanner.nextInt();
}
int secondLargestNumber = a[0];
int largestNumber = a[0];
int count = 1;
for(int i=1; i<a.length; i++) {
if(a[i] >= largestNumber) {
if(a[i] == largestNumber) {
count++;
} else {
count = 1;
}
secondLargestNumber = largestNumber;
largestNumber = a[i];
} else {
if(secondLargestNumber == largestNumber && count == 1) {
secondLargestNumber = a[i];
} else if(a[i] > secondLargestNumber) {
secondLargestNumber = a[i];
}
}
}
System.out.println("Second Largest Number: " + secondLargestNumber);
}
}
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.println("Enter array size = ");
int size=in.nextInt();
int[] n = new int[size];
System.out.println("Enter "+ size +" values ");
for(int i=0;i<n.length;i++)
n[i] = in.nextInt();
int big=n[0],sbig=n[0];
// finding big, second big
for(int i=0;i<n.length;i++){
if(big<n[i]){
sbig=big;
big=n[i];
}else if(sbig<n[i])
sbig=n[i];
}
// finding second big if first element itself big
if(big==n[0]){
sbig=n[1];
for(int i=1;i<n.length;i++){
if(sbig<n[i]){
sbig=n[i];
}
}
}
System.out.println("Big "+ big+" sBig "+ sbig);
in.close();
}