Longest sequence of a number in an array list - java

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.

Related

Method to find second highest number in an array in java

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);
}
}

Finding contiguous array

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;
}
}

Change data in an array with N range steps?

Change data in an array with N range steps, for instance, every 2 steps.
int data = new int[8];
result:
[0],[0], [0],[0], [0],[0], [0],[0];
expected:
The first two items should change to 1 and the next two will stay in 0 and so on...
[1],[1] ,[0],[0], [1],[1], [0],[0];
I know the trick with
if(position % 2 == 0)
for changing every 2 items but its changes only the first item.
any idea how to solve it?
int bars =2;
int beats = 4;
int[] pattern = new int[bars * beats];
for (int i = 0; i < pattern.length; i++) {
if(i % bars == 0 ){
pattern[i] = 0;
}else{
pattern[i] = 1;
}
}
Not the most elegant solution but works
static int[] data;
public static void main(String[] args) {
int bars = 7;
int beats = 2;
data = new int[bars * beats];
int minVal;
if(bars > beats){
minVal = Math.min(bars, beats);
}else{
minVal = Math.max(bars, beats);
}
step(minVal, 1);
for (int i = 0; i < data.length; i++) {
if(i % minVal == 0){
System.out.print("|"+ data[i]);
}else{
System.out.print(data[i]);
}
}
}
public static void step(int interval, int value) {
for (int index = 0; index < data.length; index += interval) {
for (int stepIndex = index; stepIndex < index + interval; stepIndex++) {
if (stepIndex > data.length - 1) {
return;
}
data[stepIndex] = value;
}
index += interval;
}
}
static int[] data;
public static void main(String[] args) {
int bars = 7;
int beats = 2;
data = new int[bars * beats];
int minVal;
if(bars > beats){
minVal = Math.min(bars, beats);
}else{
minVal = Math.max(bars, beats);
}
step(minVal, 1);
for (int i = 0; i < data.length; i++) {
if(i % minVal == 0){
System.out.print("|"+ data[i]);
}else{
System.out.print(data[i]);
}
}
}
public static void step(int interval, int value) {
for (int index = 0; index < data.length; index += interval) {
for (int stepIndex = index; stepIndex < index + interval; stepIndex++) {
if (stepIndex > data.length - 1) {
return;
}
data[stepIndex] = value;
}
index += interval;
}
}
Try this
int bars = 2;
int beats = 4;
int[] pattern = new int[bars * beats];
for (int i = 0; i < pattern.length; i++) {
if(i % beats < bars ){
pattern[i] = 1;
} else {
pattern[i] = 0;
}
}
This is 1 of many ways how you can achieve this. We loop through the array, incrementing by the defined interval, which you want to be 2 for example. We create another for-loop starting at the current index and end at current index + interval which will allow us to assign the value, in your case, 1, to those indices. We also check to see if the current index we're looping through is greater than the data length - 1 to ensure no array index out of bonds for non-even array sizes.
public class ChangeArrayNSteps {
public static void main(String[] args) {
ChangeArrayNSteps cans = new ChangeArrayNSteps(8);
cans.step(2, 1);
System.out.println("Data: " + Arrays.toString(cans.data));
}
private final int[] data;
public ChangeArrayNSteps(int size) {
this.data = new int[size];
}
public void step(int interval, int value) {
for (int index = 0; index < data.length; index += interval) {
for (int stepIndex = index; stepIndex < index + interval; stepIndex++) {
if (stepIndex > data.length - 1) {
return;
}
data[stepIndex] = value;
}
index += interval;
}
}
}
Output:
Data: [1, 1, 0, 0, 1, 1, 0, 0]

search palindrome number in a list of array. if there exist palindrome number in the list, return its size

Check if there exists a Palindrome Number in the list.
If found return its size, else return -1.
public class Program{
public static boolean palindrome(String list){
String reversedString = "";
for (int i = list.length() -1; i >=0; i--){
reveresedString += list.charAt(i)
}
return list.equals(revereseString);
}
}
sample input: [3,5,2,6,3,6,2,1]
palindrome number found: [2,6,3,6,2]
sample output: 5
Here is a pseudo code.
output = -1;
for (i = 0; i < list.length; i++){
num = list[i];
indices[] = \\ get all the indices which the "num" value appears, only include those indices that are greater than "i"
for (j = 0; j < indices.length; j++){
flag = true;
k = i;
for (l = indices[j]; l >= k; l--, k++){
if (list[k] != list[l]) {
flag = false;
break;
}
}
if (flag){
length = (indices[j] - i) + 1;
if (length != 1 && length > output) { // checking of length != 1 will exclude those palindromes of length 2
output = length;
}
}
}
}
return output;
Here is the full code.
public class Main {
/**
* #param args
*/
public static void main(String[] args) {
int[] list = { 3, 5, 2, 2, 6, 3, 6, 3, 6, 3, 6, 2, 2, 1 };
System.out.print(palindrome(list));
}
public static int palindrome(int[] list) {
int output = -1;
for (int i = 0; i < list.length; i++) {
int num = list[i];
ArrayList<Integer> indices = getIndices(list, i, num);
for (int j = 0; j < indices.size(); j++) {
boolean flag = true;
int k = i;
for (int l = indices.get(j); l >= k; l--, k++) {
if (list[k] != list[l]) {
flag = false;
break;
}
}
if (flag) {
int length = (indices.get(j) - i) + 1;
if (length != 1 && length > output) {
output = length;
}
}
}
}
return output;
}
public static ArrayList<Integer> getIndices(int[] list, int start, int num) {
ArrayList<Integer> result = new ArrayList<Integer>();
for (int i = start + 1; i < list.length; i++) {
if (list[i] == num) {
result.add(i);
}
}
return result;
}
}

check number of maximum and minimum element in a array

I am trying to check whether the given array has equal number of maximum and minimum array element. If their number are equal should return 1 else return 0. But instead of which return always zero.
Could you please help me?
public class MaxMinEqual {
public static void main(String[] args) {
System.out.println(MaxMinEqual.ismaxminequal(new int[]{11, 4, 9, 11, 8, 5, 4, 10}));
System.out.println(MaxMinEqual.ismaxminequal(new int[]{11, 11, 4, 9, 11, 8, 5, 4, 10}));
}
public static int ismaxminequal(int[] a) {
int maxcount = 0;
int mincount = 0;
int largest = a[0];
for (int i = 0; i < a.length; i++) {
if (a[i] > largest) {
largest = a[i];
}
if (a[i] == largest) {
maxcount = maxcount + 1;
}
}
int smallest = a[0];
for (int j = 0; j < a.length; j++) {
if (a[j] < smallest) {
smallest = a[j];
}
if (a[j] == smallest) {
mincount = mincount + 1;
}
}
if (maxcount == mincount) {
return 1;
} else {
return 0;
}
}
}
You did not reset maxcount and mincount when you find a greater or smaller value.
public static boolean isMaxMinEqual(int[] a) {
int maxcount, mincount = 0;
int largest, smallest = a[0];
for (int i = 0: a) {
if (i > largest) {
largest = i;
maxcount = 0;
}
if (i == largest) {
maxcount++;
}
if (i < smallest) {
smallest = i;
mincount = 0;
}
if (i == smallest) {
mincount++;
}
}
return maxcount == mincount;
}
Not sure if you're supposed to learn this without Data Structures, but why not take advantage of an Algorithm Efficiency Technique called presorting.
We could do something like this:
public static int ismaxminequal(int[] a) {
Arrays.sort(a);
This puts the smallest elements at the 'head' of the array and the largest elements at the 'tail'.
So, now, we must iterate from both ends to see how many of each are available (max and min).
int num_min = 1;
int num_max = 1;
int cur_value = 0; //holds a reference for comparison
cur_value = a[0];
for (int i = 1; i < a.length; i++) {
if (a[I] == cur_value)
num_min++;
else
break;
}
cur_value = a[a.length - 1];
for (int i = a.length - 1; i > 0; I--) {
if (a[I] == cur_value)
num_min++;
else
break;
}
if (num_max == num_min) {
return 1;
} else {
return 0;
}
}
}
Java 8 way. Very readable and with big arrays can be quicker that O(N) single thread implementation.
public boolean isMaxMinEqual(int[] a) {
int max = Arrays.stream(a).parallel().max().getAsInt();
int min = Arrays.stream(a).parallel().min().getAsInt();
long maxCount = Arrays.stream(a).parallel().filter(s -> s == max).count();
long minCount = Arrays.stream(a).parallel().filter(s -> s == min).count();
return maxCount == minCount;
}

Categories