How to display the last three elements of an array (my example) - java

I need to write a code that will display the last three elements of an array using for loop. 1. The arrays size can be modified and the code should cope with that. 2. The elements should be displayed as they were entered (from left to right).
import java.util.Arrays;
public class Task4 {
public static void main(String[] args) {
int[] array = {7, -3, 9, -11, 18, 99, 2, 11};
System.out.println("Current array: " + Arrays.toString(array));
System.out.println("Last three elements of an array: ");
for (int i = array.length / 2 + 1; i < array.length; i++) {
System.out.print(array[i] + " ");
/*need to display last three elements of an array using for loop.
the elements should be displayed as they were entered(from left-to-right)*/
}
}
}
The code works only for this specific array. My question was is there any alternative solutions that will work for any array size?

you can try to start from the index that equals the length-3 by changing the loop into this :
for (int i = Math.max(0,array.length-3); i < array.length; i++) {

A java stream option here:
IntStream.of(array)
.skip(Math.max(array.length - 3, 0))
.forEach(System.out::println);

Related

Maximum of each pair of index of the array

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

How to print matching elements in different positions between two arrays? (java)

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.

Sorting 2 sets of scores with array in java

I wrote following code to rank 2 sets of scores:
public class ScoreRanking {
public static void main(String[] args) {
int[] score1 = { 9, 3, 6, 19 };
int[] score2 = { 3, 3, 3, 3, 3, 5, 1 };
int[] rank1 = sortScores(score1);
int[] rank2 = sortScores(score2);
for (int i = 0; i < rank1.length; i++) {
System.out.println((i + 1) + ": " + rank1[i]);
}
System.out.println("_________\n");
for (int j = 0; j < rank2.length; j++) {
System.out.println((j + 1) + ": " + rank2[j]);
}
}
static int[] sortScores(int[] sort) {
for (int i = 0; i < sort.length - 1; i++) {
if (sort[i] < sort[i + 1]) {
continue;
} else {
int temp = sort[i];
sort[i] = sort[i + 1];
sort[i + 1] = temp;
}
}
return sort;
}
}
The first set is ordered but the second isn't. I played around with the brackets, tried a different order (int score 1... int rank1... int score2... int rank2... / int score2..., int rank2... int score1... int rank1...) - but the score2 is always "ignored". Can someone please tell me why?
I made a cold debug and I think that you're problem is with the sortScores method.
if I'm not wrong the rank2 array is sorted like this {3, 3, 3, 3, 3, 1, 5}.
The main problem that your facing is that your algorithm only change the i and i+1 elements, but what happen when your i+2 elements in lower than the i element, there the method fails doesn't do the job correctly.
If you want to develop a sorting algorithm by you I recommend that first make sort an array with 5 or 4 elements in paper and them try to understand what are you doing, them write the steps in pseudo code and finally translate into Java is longer but I guaranteed you that it will be more satisfactory, but if you want to sort the array write now them you should check the sorting algorithms on Wikipedia and take a special look on the Insertion sort is easy to understand and doesn't have much complexity.
At last, if you want to used java libraries to save time and code them you should check the Array class the sort(int[] a) method.
I hope that my answers help you to understand better this world.
Bye, Greetings from Venezuela
PD. The Insertion Sort Algorithm is this one:
public static void insertionSort (int[] array) {
for (int i=1; i < array.length; i++) {
int aux = array[i];
int j;
for (j=i-1; j >= 0 && array[j] > aux; j--){
array[j+1] = array[j];
}
array[j+1] = aux;
}
}
I'd suggest you looked up sorting algorithms as dev8080 suggested. Your sorting algorithm only goes through the list once, which is unheard of. And while your sorting algorithm may end up working for the first array, for the second array it has problems:
if (sort[i] < sort[i + 1])
With this condition you're swapping values even if they're equal, which means you're unnecessarily swapping those 3's. This might not have a visible effect, but it is a wasteful operation, and for more complex objects could produce undesirable effects.
At any rate your code only swaps the values when
sort[i] = 5
sort[i + 1] = 1
because this is the only place where the first value is less than the second one. This is why you get the result
1: 3
2: 3
3: 3
4: 3
5: 3
6: 1
7: 5
It looks like you're trying to implement an variant of bubble sort, in which case you should check out this link:
https://en.wikipedia.org/wiki/Bubble_sort
keep in mind bubble sort is not very efficient for larger lists

Basic Array Skills: Label Each Element

I have to perform the following basic skills with arrays: Here is a list of everything I had to do:
a) Create an array x of doubles with an initializer list that contains the following values: 8, 4, 5, 21, 7, 9, 18, 2, and 100.
b) Print the number of items in the array.
c) Print the first array item.
d) Print the last array item. Be careful to choose the right index.
e) Use a standard for loop to print all the values in the array.
f) Use a standard for loop to print all the values in the array with labels to indicate the location of each element, such as [0] = xx
g) Use a standard for loop to print all the values in the array in reverse order.
h) Use an enhanced for loop to print all the values in the array.
I am having a lot of trouble with f), I saw that you could label using "JLabel" which I did not learn in my class but I wasn't sure if it could be applied here, here is my code so far. If "JLabel" can't be used, what else would I be able to do? Any help will be appreciated, Thanks!!!
public static void main(String[] args) {
double[] x = {8, 4, 5, 21, 7, 9, 18, 2, 100};
double temp;
System.out.println("The number of items in the array is " + x.length);
System.out.println("The first array item is " + x[0]);
System.out.println("The last array item is " + x[8]);
for(int i = 0; i < 9; i++)
{
System.out.println(x[i] + " ");
}
//F
//JLabel labels[] = new JLabel[8];
//for (int i = 0; i < 9; i++)
//{
//labels[i] = new JLabel("Label" + i);
//}
for(int i =x.length - 1; i >= 0; i--)
{
System.out.println(x[i] + " ");
}
for (double val : x)
{
System.out.println(val + " ");
}
}
}
JLabel is a Swing GUI component. It represents a text label in a GUI. It is not what you want to use here (although I can understand your attraction to the "Label" in its name -- but, you don't make ham with a hammer).
Your requirement is simply "print all the values in the array with labels to indicate the location of each element, such as [0] = xx". That is, "labels" in the dictionary sense, not "labels" as in some explicit special "label" class.
It's simpler than you think, you may be over-complicating this! For example:
for (int i = 0; i < x.length; i ++) {
// 'i' is the index
// 'x[i]' is the value
System.out.println( /* fill this in */ );
}
I'll leave the details as an exercise to you. Hint: If i==1 and x[i]==42 then the output should be [1] = 42.

Java Arrays.sort resets results to all zeros

I am using Java Arrays.sort in order to sort elements of a two dimensional array:
int[][] RAM = new int[4][10000];
I fill the RAM array with integers and then call:
for (i=0;i<4;i++){
Arrays.sort(RAM[i]);
System.out.println(i);
}
This results in all elements of RAM[][] being filled with zeros. What am I doing wrong?
Did you actually fill the Array with numbers first?
And if you did, you are only printing out the First part of your 2D array. You need to print out all 40,000 entries. 10,000 for each array in array. So [0][0...9999], [1][0...9999] etc.
public static void show (int [][] list)
{
System.out.println ("- show: -");
for (int [] ia : list) {
for (int i : ia)
System.out.print (i + ", ");
System.out.println ();
}
System.out.println ("---");
}
static Random random = new Random ();
public static void main (String [] args)
{
int[][] RAM = new int[4][2];
for (int i = 0; i < 4; ++i)
{
for (int j = 0; j < 2; ++j)
{
RAM[i][j] = random.nextInt (20);
System.out.print (i*2 +j);
}
}
show (RAM);
for (int i=0; i<4; i++) {
Arrays.sort (RAM[i]);
}
show (RAM);
System.out.println ();
}
Result:
- show: -
8, 13,
12, 10,
16, 3,
7, 1,
---
- show: -
8, 13,
10, 12,
3, 16,
1, 7,
---
I think the reason is that you didn't set a value for all elements of your array. For the item you didn't initialize, the default value is 0. Thus when you sort the all items in the array, the 0s are swapped to the first part of your array. If you output the first parts of the array, all you see are zeros. I guess so.

Categories