Method taking in 2 arguments (array of ints, and a single int) - java

I've created a method, that, given a array of numbers and an integer n, it calculates the longest occurrence of the integer n. For example 1 0 0 0 1 1 1 1, given the number 1, the longest sequence is 4. I'm just using 0's and 1's at the moment to keep it simple, however I'm really stuck on implementing my main method to test this function - I'm not sure how to separate the integer "n" and the array of ints when reading from the command line, and I'm hoping I could be given some pointers/help. Here's my code:
public class OneB {
public static int longestSeq(int[] nums, int n) {
int max = 0;
int curLength = 0;
for (int i = 0; i < nums.length; i++) {
if (i == n) {
curLength++;
if (curLength > max)
max = curLength;
} else
curLength = 0;
}
return max;
}
public static void main(String[] args) {
int[] nums = new int[args.length-2];
int n = Integer.parseInt(args[args.length-1]);
for (int i = 0; args.length-1 > i; i++) {
nums[i] = Integer.parseInt(args[i]);
}
int result = longestSeq(nums, n);
System.out.println(result);
}
}
What I'm aiming is for the last number in the command line to be used as the integer n, whilst everything before that will be used as the array nums.
With the input 1 1 0 0 0 1 1 1 1 1 (the last 1 being my "n" value - 4 being the expected output") I get the error:
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 8
at OneB.main(OneB.java:26)

Check the JavaDoc for ArrayOutOfBounds.
Then put a break point in your code (you already have the information needed to figure out which line) and step through your code slowly, watching the values of all your variables.

Related

Plus Multiply | December Long Challenge Division 2

The first line of the input contains a single integer T denoting the number of test cases. The description of T test cases follows.
The first line of each test case contains a single integer N.
The second line contains N space-separated integers A1,A2,…,AN.
Output
For each test case, print a single line containing one integer ― the desired number of pairs.
Example Input
2
3
2 4 2
3
0 2 3
Example Output
1
0
My solution looks like:
class Codechef {
public static void main (String[] args) throws java.lang.Exception {
ArrayList<Integer> resultList = new ArrayList<Integer>();
Scanner scanner = new Scanner(System.in);
int T;
T = scanner.nextInt();
for(int i = 0; i < T; i++) {
int N;
N = scanner.nextInt();
int A[] = new int[N];
for(int j = 0; j < N; j++) {
A[j] = scanner.nextInt();
}
quick_sort(A, 0, N-1);
int pos = 0, pairs = 0;
while(pos < A.length - 1) {
if(A[pos] == A[pos + 1]) {
pos += 2;
pairs += 1;
} else {
++pos;
}
}
resultList.add(pairs);
}
for(int pairCount : resultList) {
System.out.println(pairCount);
}
scanner.close();
}
}
It successfully runs the example test cases but fails on submission, My question is, if the input is something like 1 1 2 2 1, then what should be the answer, 3? as there are 2 pairs of 1, and 1 of 2's.
Also, what will be the suggested data structure to be used for this purpose, Java with primitive data types is taking too much longer to execute it with 40,000 input values. What's wrong with my solution
To answer your first question, I'd say yes that each pair of 1's would count separately so you'd get 3.
I think your code is failing since you're only counting touching pairs after you sort.
For example,
1 1 1, you find the first pair at index 0/1, but then advance pos += 2.This means you're missing the two other pairs of 1's.
Your solution seems to be O(nlogn) because of sorting but I can think of a O(n) solution.
int[] backing = new int [10];
for (int j = 0; j < N; j++) {
int x = scanner.nextInt();
backing[x]++;
}
//At this point, you have a backing array with the frequency of each integer
You'll want something similar to this to calculate the number of pairs. It's the frequency of each integer choose 2, since you want to choose each occurrence of a pair.
So for example if you know you have 5 1's, then you'll compute:
5!/(2!*3!) = 10

Find Maximum Positive Index

You are given an array A. We define a term Positive difference index as the count of elements between the two indexes i and j (both inclusive) such that i<j and A[i]<A[j].
Now for the given array, you have to find the maximum positive difference index. It is assured that the test case will be valid such that there exists an answer.
Input format
First line : T i.e Number of test cases.
For each test case :
First line : N
Second line : N space separated integers denoting the element of the array.
Output format
Print the answer to each test case in a separate line and it is given that answer always exists.
Sample Input
1
6
5 3 2 1 1 4
Sample Output
5
Explanation
let i=2 and j=6 then A[i]<A[j] and total elements between them is 5 so the maximum answer that can be achieved is 5.
I had tried to find maximun number from an array and minimum number from array such that A[i]<A[j]. With sample input it worked but for when I submitted the question on hackerearth it displayed none test cases were passed. Can anyone please me help to understand the question and program?
Below program I have written
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class Test {
public static void main(String[] args) throws IOException {
BufferedReader br = null;
try {
br = new BufferedReader(new InputStreamReader(System.in));
String line = br.readLine();
int totalTest = Integer.parseInt(line);
for(int i=0;i<totalTest;i++) {
line = br.readLine();
int totalElements = Integer.parseInt(line);
line = br.readLine();
String strArr[] = line.split(" ");
int elements[] = new int[strArr.length];
for(int j=0;j<strArr.length;j++) {
elements[j] = Integer.parseInt(strArr[j]);
}
System.out.println(findMaximumPositiveIndex(elements));
}
}catch(Exception e) {
e.printStackTrace();
}
finally {
if(br!=null)
br.close();
}
}
public static int findMaximumPositiveIndex(int[] arr) {
int max=arr[0];
int maxIndex = 0;
int minIndex=arr[0];
int min=0;
for(int i=0;i<arr.length;i++) {
if( min==0 ) {
min = arr[i];
minIndex=i;
}
if(arr[i] < min) {
min = arr[i];
minIndex = i;
}
if(arr[i] > max) {
max = arr[i];
maxIndex = i;
}
}
return (max - min) + 1;
}
}
The maximum and minimum values from the array, in most cases they won’t help you. So don’t find those. In the example in the question the maximum value is 5 and the minimum is 1. Neither of those two values are involved in calculating the output. Instead the values 3 and 4 are because they are the farthest apart values that fulfil the condition A[i] < A[j]. The output should be 5 because the part of the array 3 2 1 1 4 has length 5. Or “the count of elements between the two indexes i and j (both inclusive)”, as the challenge puts it.
Instead you find the output from the min and max values as (5 – 1) + 1 = 5 (I think; I haven’t studied your code thoroughly). Coincidentally you hit the correct output in this single case. You haven’t done it correctly.
Other examples:
For 2 1 2 1 2 1 the answer is 4 because the part 1 2 1 2 has length 4 and 1 < 2.
For 40 90 10 60 the answer is 4 too because 40 90 10 60 has 4 elements in it and 40 < 60.
I understood that you asked for help understanding the problem, not for solving it, so I am happy to leave that pleasure to yourself.
Thanks for helping to understand the problem statement.
I have modified the code
public static int findMaximumPositiveIndex(int[] arr) {
int min=arr[0],max=arr[0],minIndex=0,maxIndex=0;
int maximumIndex = 0;
for(int i=0;i<arr.length;i++){
min = arr[i];
minIndex=i;
boolean isMaxPresent = false;
for(int j=i;j<arr.length;j++)
{
if(arr[j] > min){
max = arr[j];
maxIndex = j;
isMaxPresent = true;
}
}
if(maximumIndex < ((maxIndex - minIndex) +1) )
maximumIndex = (maxIndex - minIndex) + 1;
}
return maximumIndex;
}
which fulfills all the test cases. Thanks

Exception in thread java.lang.ArrayIndexOutOfBoundsException: 5

I'm a newbie who is trying to complete the below tutorial
// Create a method called countEvens
// Return the number of even ints in the given array.
// Note: the % "mod" operator computes the remainder, e.g. 5 % 2 is 1.
/*
* SAMPLE OUTPUT:
*
* 3
* 0
* 2
*
*/
Below is my code
public static void main(String[] args) {
int a[] = {2, 1, 2, 3, 4};
countEvens(a); // -> 3
int b[] = {2, 2, 0};
countEvens(b); // -> 3
int c[] = { 1, 3, 5};
countEvens(c); // -> 0
}
public static void countEvens(int[] x){
int i = 1;
int count = 0;
while ( i <= x.length){
if (x[i] % 2 == 0){
count ++;
}
i ++;
}
System.out.println(count);
}
The code can be run, but I get the below error message
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 5
at apollo.exercises.ch05_conditionals.Ex5_CountEvens.countEvens(Ex5_CountEvens.java:23)
at apollo.exercises.ch05_conditionals.Ex5_CountEvens.main(Ex5_CountEvens.java:10)
May I know what I'm doing wrong here?
The line
while ( i <= x.length)
should be
while ( i < x.length)
If the length of xis 5, for example, the indices are 0, 1, 2, 3 and 4. The index goes from 0 up to one less than the length of the array.
However the tidiest way to do this is to use a for each loop rather than a while loop:
public static void countEvens(int[] x) {
int count = 0;
for (int number : x)
if (number % 2 == 0)
count++;
System.out.println(count);
}
'i' should go from 0 to length()-1, because array indices start at 0, and the index of the last element is length()-1.
Therefore, a correct version of your code would be:
public static void countEvens(int[] x){
int i = 0;
int count = 0;
while ( i < x.length){
if (x[i] % 2 == 0){
count ++;
}
i ++;
}
System.out.println(count);
}
For your specific purpose, a for loop would be simpler.
for(int i = 0; i< x.length(); i++){
if(x[i]%2==0){
count++;
}
}
At while ( i <= x.length), you're looping until i is equal to the length of x. The last index of an array is always length - 1, so change the less-than-or-equals (<=) to just less-than (<). Also, initialize i to 0, as Java arrays are zero-based.
Arrays in Java (and most other languages) are indexed starting at 0. However the length of an array is the count of the elements in the array. So for your array a[]
int a[] = {2,1,2,3,4};
The index goes up to 4, whereas the length is 5.
You are getting an index out of bounds error because you are iterating through the array from 1~5 because of the <= (less than equal to) operator, but the indices of the array are 0~4. When you access each element of the array you should use
if (x[i-1] % 2 == 0) //iterates from 0~4 rather than 1~5
otherwise you can set the iterator int i = 0; and use the less than < operator to ensure the iterator moves 0~4

Length and location of longest contiguous sequence of equal values where just before and just after are smaller

I have a problem that asks:
Write a program that converts its input arguments into an array of
integers, and then finds the length and location of the longest
contiguous sequence of equal values where the values of the elements
just before and just after this sequence are smaller.
For example, if
the command line arguments are “1 2 2 2 2 5 5 5 3” your program should
output the numbers 5 3 (the first number is a zero-based offset, and
the second number is the length of the subsequence). If a contiguous
subsequence appears at the beginning or end of the array, treat this
as a special case;e.g.,for input “5 5 5 5 3 8 8 8 1”your output should
be 0 4 (and not 5 3). If there are multiple subsequences that satisfy
the above condition, then output the first one.
Updated code:
public class LongestPlateau {
public static void main(String[] args) {
// TODO - Your solution
int N= args.length;
int [] array = new int [N];
int new_length=0;
int location=0;
int max=0;
int current_length=0;
//assign digits into array
for (int i=0; i < N; i++){
int number = Integer.parseInt(args[i]);
array [i] = number;
}
int compare=array[0];
for (int l=0; l<N; l++){
if (array[l] < compare){
current_length=0;
compare = array[l];
}
else if (array[l] == compare){
current_length+=1;
compare = array[l];
}
else if (array[l] > compare){
compare=array[l];
l++;
}
compare= array[l];
for (int b=0; b<N; b++){
if (current_length > max){
max = current_length;
location = array[l];
new_length=max-1;
}
else if (current_length==1){
new_length=max;
}
}
}
System.out.println(location);
System.out.println(new_length);
}
}
Issue is that for the input of "1 2 3 4" I continously get an Array Index out of bounds error.
Before you start writing code, try and think how a human would have solved it.
e.g.
For every item in the input, compare it to the previous, if it's larger, start a new sequence length check (write 0 in your notebook under - "current sequence length)), if it's the same, increase it by 1, if it's less, mark that sequence length as complete. if it's larger than your largest sequence length so far (started with 0) then this is now your largest sequence, if not, ignore that sequence length and move on to the next character. (or something like this)
write these instructions to yourself as a human, and try to follow them, and fix them as you find edge cases. Once you have a working human language algorithm, writing the code will be almost self driven.
You really need to post the specific issue you are seeing, how your actual results differ from your expected results, and what solutions you have attempted.
In any case, as for the general "how to proceed" question, I find that it often helps to work out these types of problems on paper first. Write down your sequence and step through it, observe what information you need to keep track of and what logic you need to apply to produce the desired results. Once you are able to do this, it will be far more straightforward to translate your clearly thought out algorithm into concrete code.
It appears you are at least somewhat on the right track parsing and storing your integer array, but you are a bit misguided with your [t+?] lookaheads. If you write this out and step through it by hand, you may be surprised at what you come up with.
Here is a full program description with test cases:
Given an array of integers int A[], find the length and location of the longest contiguous sequence of equal values for which the values of the elements just before and just after this sequence are smaller.
You should just print these two numbers (first is the length and second is the starting index of the plateau).
To complete the definition, we can consider there are imaginary index positions at A[-1] and A[A.length] where A[-1] < A[0] and A[A.length] < A[A.length-1]. Therefore, the plateau can start/end at both ends of array A. This condition guarantees the existence of a plateau. A plateau can be of length 1.
Example 1:
java LongestPlateau 1 2 2 2 2 1
With this command line arguments, program should print:
4
1
Example 2:
java LongestPlateau 1 2 2 2 2 3
With this command line arguments, program should print:
1
5
Example 2:
java LongestPlateau 3 2 2 2 1 2 1 1 1 2 2 0 1 1 1 1 0
With this command line arguments, program should print:
4
12
Example 2:
java LongestPlateau 3 2 2 2 2 2 2 1 2 1 1 1 2 2 0 1 1 1 1
With these command-line arguments, the program should print:
4
15
Here is my solution:
public class LongestPlateau {
private static int[] parseInputArray(String[] args) {
int[] value = new int[args.length+1];
for(int i = 0 ; i < args.length; i++){
if (i == args.length-1) value[i] = 0; // this imaginary last value of the array ensures that if the plateau is the last value of the array, then it outputs the correct answer
value[i] = Integer.parseInt(args[i]);
}
return value;
}
public static void printLargestPlateau(int[] values) {
int biggestStartIndex = -1;
int biggestLength = 0;
int currentIndex = 1;
int currentPlateauStartIndex = 1;
int currentLength = 1;
boolean plateauStarted = false;
while (currentIndex < values.length) {
if(isStartOfPlateau(currentIndex, values)){
currentLength = 1;
plateauStarted = true;
currentPlateauStartIndex = currentIndex;
} else if (isEndOfPlateau(currentIndex, values)) {
if(plateauStarted && currentLength > biggestLength){
biggestLength = currentLength;
biggestStartIndex = currentPlateauStartIndex;
}
plateauStarted = false;
currentLength = 1;
} else {
currentLength++;
}
currentIndex++;
}
System.out.println(biggestLength +"\n"+biggestStartIndex);
}
private static boolean isStartOfPlateau(int index, int[] values){
if(index <= 0){
return false;
}
return values[index-1] < values[index];
}
private static boolean isEndOfPlateau(int index, int[] values){
if(index <= 0){
return false;
}
return values[index - 1] > values[index];
}
public static void main(String[] args) {
int[] values = parseInputArray(args);
printLargestPlateau(values);
}
}

How can I locate and print the index of a max value in an array?

For my project, I need to make a program that takes 10 numbers as input and displays the mode of these numbers. The program should use two arrays and a method that takes array of numbers as parameter and returns max value in array.
Basically, what I've done so far is used a second array to keep track of how many times a number appears. Looking at the initial array, you will see that the mode is 4. (Number that appears most). In the second array, the index 4 will have a value of 2, and thus 2 will be the maximum value in the second array. I need to locate this max value in my second array, and print the index. My output should be '4'.
My program is good up until I attempt to produce the '4', and I've tried a few different things but can't seem to get it to work properly.
Thank you for your time!
public class arrayProject {
public static void main(String[] args) {
int[] arraytwo = {0, 1, 2, 3, 4, 4, 6, 7, 8, 9};
projecttwo(arraytwo);
}
public static void projecttwo(int[]array){
/*Program that takes 10 numbers as input and displays the mode of these numbers. Program should use parallel
arrays and a method that takes array of numbers as parameter and returns max value in array*/
int modetracker[] = new int[10];
int max = 0; int number = 0;
for (int i = 0; i < array.length; i++){
modetracker[array[i]] += 1; //Add one to each index of modetracker where the element of array[i] appears.
}
int index = 0;
for (int i = 1; i < modetracker.length; i++){
int newnumber = modetracker[i];
if ((newnumber > modetracker[i-1]) == true){
index = i;
}
} System.out.println(+index);
}
}
Your mistake is in comparing if ((newnumber > modetracker[i-1]). You should check if the newnumber is bigger then the already found max. That is if ((newnumber > modetracker[maxIndex])
You should change your last rows to:
int maxIndex = 0;
for (int i = 1; i < modetracker.length; i++) {
int newnumber = modetracker[i];
if ((newnumber > modetracker[maxIndex])) {
maxIndex = i;
}
}
System.out.println(maxIndex);
You could change last part to:
int maxIndex = 0;
for (int i = 0; i < modetracker.length; i++) {
if (modetracker[i] > max) {
max = modetracker[i];
maxIndex = i;
}
}
System.out.println(maxIndex);

Categories

Resources