I need to create an array, compare each pair of this array, and then find and print the largest element of each pair. I have created an array like below, but it's printing me only the two largest of the whole array!
public class Main {
public static void main(String[] args) {
int[] arr = {1, -5, 2, 6, 10, 7};
int a = arr[0];
int b = arr[1];
for (int i = 0; i<arr.length; i++) {
for (int j = i + 1; j < arr.length; j++) {
if (a > b || b > a) {
a = arr[i];
b = arr[j];
}
}
}
System.out.println(a);
System.out.println(b);
}
}
In the example below, I have 3 pairs (6 elements) and I want to get maximum of each pair as an example:
Input: {1, -5, 2, 6, 10, 7}
Output: 1, 6, 10
I appreciate any help you can provide.
Your program does not print the two largest numbers. It prints the two last numbers of the array. If you add a 200 in the mid of the array, it will still print 10 and 7.
Also, the System.out.println()-lines are outside any loop, so they will run only once.
If you want to get the higher number out of the first and second, the third and fourth, fifth and sixth element and so on (due to the expected output, I assume this is what you want to get), then the for-loop will fail like this. On each run of the loop, it will check if a > b or b > a. If that's the case, a gets the value of arr[i] and b the value of arr[j]. On the last run, i will be the second last value and j the last value of the array, so you will always get the last two elements. Unless you compare two times the same value in the array, then a and b will get the same value and nothing will change anymore from there.
If you want to compare the pairs like I described, then maybe you should instead try something like this:
for(int i = 0; i < arr.length; i+=2)
{
if(!(i == arr.length-1)) // in case there is no i+1 index anymore
{
if(arr[i]>arr[i+1])
{
System.out.println(arr[i]);
}
else if(arr[i+1]>arr[i])
{
System.out.println(arr[i+1]);
}
}
}
Related
So I was trying to produce an arraylist where the even indexes were all filled. Something like this [1, -, 1, -, 1, -........]. But it's giving me an index out of bounds error. Why is that?
import java.util.ArrayList;
class Main {
public static void main(String[] args) {
ArrayList<Integer> a = new ArrayList<>(10);
for (int i=0; i<11; i+=2) {
a.add(i, new Integer(1234));
}
}
}
Remember indices always start with 0.
You've created an arraylist with size 10, which means you should iterate through index 9, not 10.
Your for loop should be:
for (int i = 0; i < 10; i += 2)
Arrays use zero based indexing meaning you can reference a[0] through a[9]. so your constraint in the for loop
Should be i < 10. I’ll edit this answer and give more detail when I get home.
First, you loop constraint is off, for an array (and ArrayList) of size 10, indices are 0 through 9, means you need to check for i < 10.
Second, the parameter of ArrayList constructor (10 in this case) is the capacity, but not size - it's still empty, no actual elements in there. So you need to add zeroes (or nulls) in the loop too:
for (int i = 0; i < 10; i++) {
if (i % 2 == 0) {
a.add(1234);
} else {
a.add(0); // or a.add(null)
}
}
I have two arrays. Array1 holds 5 randomly generated numbers and array2 holds 5 guesses inputted by the user. I'm trying to count the matches but the only matches that are being read are the ones in the same position. How can I get my program to count the same number even if it's in a different position?
Here's what I've got so far:
int count = 0;
for (i=0;i<array1.length;i++){
if(array1[i] == array2[i]){
count = count +1;
}
}
System.out.println("matching numbers : "+count);
If the two arrays are both small, i.e. each array contains only five elements, then you need a nested loop. For each element in the random numbers array, iterate through the guesses array.
int count = 0;
for (int i = 0; i < array1.length; i++) {
for (int j = 0; j < array2.length; j++) {
if (array1[i] == array2[j]) {
count++;
}
}
}
System.out.println("matching numbers : "+count);
Note that the above is appropriate when both arrays are small. When both arrays are large the above is not appropriate.
You just need the intersection between the two arrays and then to count the size of the result array.
So you can avoid to manually loop over the two arrays just simply using the retainAll method on List class:
https://docs.oracle.com/javase/7/docs/api/java/util/List.html#retainAll
Here is a junit test that shows how to solve using this approach:
#Test
public void TestArraysIntersection() {
Integer[] randomlyGenerated = {1,2,3,4,5};
Integer[] userInput = {4,2,5,3,6};
System.out.println("Randomly generated numbers are: " + Arrays.toString(randomlyGenerated));
System.out.println("Number selected by the user are: " + Arrays.toString(userInput));
List<Integer> intersectionList = new ArrayList<>(Arrays.asList(randomlyGenerated));
intersectionList.retainAll(Arrays.asList(userInput));
System.out.println("Matching numbers are " + intersectionList.size() + " and the values are: "+ intersectionList);
}
Test result is the following:
Randomly generated numbers are: [1, 2, 3, 4, 5]
Number selected by the user are: [4, 2, 5, 3, 6]
Matching numbers are 4 and the values are: [2, 3, 4, 5]
You need to loop through both arrays. In your code you are comparing each element of one array with the element in the same position of the other array, but you have to compare each element of one array with every element of the other array, like this:
public class MyClass {
public static void main(String args[]) {
int[] numbers = {1, 3, 0, 6};
int[] guesses = {3, 8, 5, 1, 2};
for (int i = 0; i < numbers.length; i++) {
for (int j = 0; j < guesses.length; j++) {
if (numbers[i] == guesses[j]) {
System.out.println("A match on positions "+i+" and "+j+". "+numbers[i]+" = "+guesses[j]);
}
}
}
}
}
Output:
A match on positions 0 and 3. 1 = 1
A match on positions 1 and 0. 3 = 3
Of course, instead of outputting the values that match, you can instead increment a count like in your example, and show instead how many elements matched.
i am trying to formulate a for loop that will take an array, for instance of 5 elements, and will allow me to treat a[0] as if it is after a[4], and a[4] as if it was before a[0].
I cannot change the array, and it stores a thread in each element, so i would rather make it as simple as possible to not corrupt the contents of the thread(threads are synchornized and using reentrantlock - so the question is only about array).
I want to make this simple for loop:
for (int i = 0; i < ARRAYSIZE; i++)
to allow me to treat it as if it was a cyclic array. I thought of using the mudolo operation to achieve that, but that doesn't work either. here's what i tried:
for (int i = i+1 % n; i < ARRAYSIZE; i++)
but that doesn't work as well. What I am trying to do is basically check if array[i] is larger than array[i+1] or array[i-1].
would appreciate your assistance.
Use the modulo operator on the loop variable i by the size of the array:
public static void main(String [] args) {
int [] arr = {1, 5, 4, 3, 3, 4, 3, 1};
int ARRAYSIZE = arr.length;
for (int i = 0; i < ARRAYSIZE; i++) {
int index = i % ARRAYSIZE;
int indexUpper = (i + 1) % ARRAYSIZE;
//access array using index
if (arr[index] == arr[indexUpper]) {
System.out.format("Elements %d and %d are equals.\n", index, indexUpper);
}
}
}
Note how for the upper value you want to cycle through, you need to do (i + 1) % ARRAYSIZE to ensure you get the next element. To get the element two places over, add 2 instead, or whatever modifier you choose.
This test shows how elements 7 and 0 are equal because it is cyclical.
Output:
Elements 3 and 4 are equals.
Elements 7 and 0 are equals.
An integer array stores values 3,2,3,4,5. I am trying to create a program that increments these values by 2 and then saves the result into the same array using a for loop. I tried but something is wrong with my code, here:
public class ArrayClass {
int a[] = {2, 3, 3, 4, 5};
}
public class ArrayObject {
public static void main(String[] Ella) {
int a[] = new int[5];
int i;
for (i = 2; i < a.length; i = i + 2) {
a[i] = i + 2;
System.out.println(a[i]);
}
}
}
This should work:
for (i = 0; i < a.length; i++) {
a[i] += 2;
System.out.println(a[i]);
}
You see, when increasing every single value of an array, the index has to be 0 and max the array's length. By adding one to i, the indexing of the array increases by one, which means the next number will be increased by two. what you did was add two to the "i" variable which means that only 3 of the varialbes would have been changed.
Please make below change to your code.It will work.
for (i = 0; i < a.length; i++) {
a[i] = a[i] + 2;
System.out.println(a[i]);
}
The error is that when you do i = i + 2, you are just incrementing the position index, not the actual value in that position.
you need to do:
a[i] = a[i]+2;
Let me explain what a[i] is:
|3|2|3|4|5|
1 2 3 4 5
The first row are the values. The second row is the index. "Index" means the position number of each of positions in the array.
Another problem is that, when you initialise i, it need to be i=0. That is because i array indices (plural of index) always start from 0. That means that a[0] is the first position in the array That would be number 3 from your data set.
So I am in the AP Computer Science class in High School so I'm not very experienced. I have a program to do that requires me to read in numbers from a file, put those numbers into an array and then remove all of the 0's from the array.
So if the numbers are: 0,2,4,6,0,5,3,5...
I would need to create an array: [0,2,4,6,0,5,3,5]
and then remove the 0's: [2,4,6,5,3,5]
I have to do this using arrays and I am not allowed to create a second array to do this. I have looked all over online and the Java API's to find a method that can remove an element from an array but I simply can't find one. If somebody has any idea of one that I can use or a direction to steer me in, your advice would be much appreciated.
THIS IS THE QUESTION WORD FOR WORD:
1. Write a program that reads a text file(compact.txt) and stores the integers in an array. Your instructor will provide this text file.
2. Write a method compact that removes all zeroes from the array, leaving the order of the elements unchanged. All local variables within this function must be scalar. In other words, you may not use a second array to solve the problem.
3. Do not solve the problem simply by printing out only the non-zero values in the array. The compact method must remove all zeroes from the array.
You could try the following: Since you cannot modify the length of the array, you can arrange it so you put all zeroes at the end of the array and with value -1 (this is optional, just to indicate they are zeroes).
public static void main(String[] args)
{
int[] arr = { 0, 1, 2, 0, 3, 0, 4, 0, 5, 6, 7 };
int[] arrWithoutZeros = compact(arr);
for (int i : arrWithoutZeros) {
System.out.println(i);
}
}
private static int[] compact(int[] arr)
{
for (int i = 0; i < arr.length; i++) {
if (arr[i] == 0) {
int j = 0;
for (j = i; j < arr.length - 1; j++) {
arr[j] = arr[j + 1];
}
arr[j] = -1;
i--;
}
}
return arr;
}
Output:
1
2
3
4
5
6
7
-1
-1
-1
-1
Note: This meets the question requirements:
Leaves the order of elements unchanged (it changes its position, but not the order)
Don't use a second array
Not solved by just printing the non-zero elements
Removes zeros from array (they are now -1)
I'm not normally a fan of doing homework, but I found this one interesting and impossible as written, so here goes.
This is much like Christian's answer, but I'm using Integer instead of int so that I can set the 0s to null instead of some other integer. I've also avoided the extra loop he has to copy every remaining value down on every single 0, instead iterating the array once and then iterating the tail only once to set the null values.
public class ArrayCompact {
private static Integer[] ARRAY = { 1, 3, 5, 0, 7, 9, 0, 2, 0, 4, 6, 0, 8, -1, 0 };
public static void main( String[] args ) {
printArray( compact(ARRAY ));
}
public static Integer[] compact( Integer[] ints ) {
int j = 0;
for ( int i = 0; i < ints.length; i++ ) {
if ( ints[i] != 0 ) {
ints[j++] = ints[i];
}
}
for ( int i = j; i < ints.length; i++ ) {
ints[i] = null;
}
return ints;
}
public static void printArray( Integer[] ints ) {
for ( Integer i : ints ) {
System.out.print( i + " " );
}
}
}
Output 1 3 5 7 9 2 4 6 8 -1 null null null null null Technically I guess you could just not print the nulls, since that's not not printing 0s...
Another Edit:
(I think previous answer is still meaningful and I am keeping it at the end. This edit is mainly for suggestion specific to the homework requirement)
Base on the question, the compact logic treat 0 as something that is "meaningless" and need to be "removed". Therefore we don't really need some kind of special value after we "shrink" the array. Simply keeping it as 0 will help.
Apart from the "copy [i+1,end] to i" method, there is another (easier and possibly faster) method that you can do to "remove" the zeros.
Basically what you need is, iterate through the array. If you encounter a 0, then find the first non-zero value after that position, and swap the zero with that non-zero value.
Which looks like this in psuedo code:
for (i = 0; i < arr.length; i++) {
if (arr[i] == 0) {
for (j = i+1; j < arr.length; j++) {
if (arr[j] != 0) {
arr[i] = arr[j];
arr[j] = 0;
break;
}
}
}
}
// arr is "shrinked" here
Then it is your choice to return an actually shrinked copy of array, or simply return the "so-called-shrinked" array with 0s at the end.
Something for you to think of:
First, in Java, size of array is fixed, therefore, it is not possible to shrink array's size. Therefore, it is IMPOSSIBLE to have a result array with less elements without creating a new array
If it is fine for you to leave unused element at the end as some special values (e.g. -ve, or 0 etc), the removing element at position i from array essentially means:
copy array elements [i+1 to end] to position i, and replace arr[end] with special empty value
e.g. [1, 3, 5, 7, 9]
If I want to remove index 2, what I need to do is to copy element 3-4 to position 2:
[1,3,5,7,9] -> [1,3,7,9,9]
^^^ ^^^
and replace end element with some special value (e.g. -1 in this example):
[1,3,7,9,9] -> [1,3,5,7,-1]
Array copy can be done easily by using System.arrayCopy()
Have just seen update in your question.
Most of my answer is still valid, and here is some extra update with regards to your question:
If you are sure that no Integer.MIN will appear in your input, then use my above mentioned approach, and update the input array accordingly.
You may consider using Integer[] instead of int[], so that you can put null
This is the most "normal" approach, but given your requirement, this may or may not be valid. The question ask you to have only scalar LOCAL VARIABLES. Which implies to me that, if I don't create another variable, I can still return another array (seems that the question is only trying to stop you using another array in process of compacting). Just follow what I have mentioned above, however, instead of replacing the end position with some special value, just keep a local var which is array length. Whenever you remove an element (by copying [i+1, 0] to position i), decrement the array length var. At the end, return a new copy of "shrinked" array by using Arrays.copyOf(oldArray, newLength).
Here is a piece of psuedo-code for point 3:
int[] compact(int[] input) {
int arrSize = input.length;
int i = 0;
while (i < arrSize) {
if (input[i] == 0) {
copy input[i+1 to end] to input[i to end-1]
arrSize--;
} else {
i++;
}
}
return Arrays.copyOf(input, arrSize);
}