Java how to take second element of array - java

I'm working on an assignment that requires the user to input an undecided number of integers, and then those numbers are to be used in other calculations. But for example if I have these 6 numbers. 1 2 3 4 5 6 and I want to extract only 2 4 and 6 from the input how would I do that? (make notices that this is just an example, the user can put in 20 different numbers, or only 4) I just want to be able to chose to pick every second element. To add more info, I need the first number in the array to be for one calculation, then the second for another calculation and then the first and the second. Basically I want to be able to assign every even array index numbers to a integer and every odd array index numbers to another integer. Like this :
"if (i % 2 == 0){int first = numbers [i];
System.out.println("This is the first" + first) }
else if (i % 2 == 1) { int second = numbers [i] ; System.out.print("This is the second. " + second);}"
But when I do so, it only appears in the first one..

you need to collect all of elements that index is odd in an array due to array index start at 0.
// all of the second elements in numbers are collected into partial array
int[] partial = new int[numbers.length >> 1];
// the initial value of i=1 means iterate the first second element at first
// i+=2 means iterate the next second element in array
for(int i=1;i<numbers.length;i+=2){
partial[(i-1)>>1] = numbers[i];
}

If you are familiar with Java 8 streams then you could use an IntStream to generate the indices and then pick out every odd one:
int[] everySecond = IntStream.range(0, array.length)
.filter(i -> i % 2 == 1).mapToInt(i -> array[i]).toArray();

So just for clarification you want every second iteration of the array without the order of the numbers having any affect? So the array of numbers could be 4,2,6,8 and the return should be 2 and 8 in this example?
If this is the case then you can can assign the for loop to only read every second iteration.
To do this you will need the length of the array.
int arrLength = arr.length;
for (int i = 1; i < arr.length; i = i+2) {
#dosomething
}

// This is from user
int[] userInput = {};
int[] pickedNumbers = new int[userInput.length/2];
if(userInput.length > 1)
{
for (int i = 1; i < userInput.length; i = i + 2)
{
pickedNumbers[i / 2] = userInput[i];
}
}
// pickedNumber is the array you can use.

Related

Finding the longest run of duplicate numbers in an ArrayList? (Beginner java)

This is my first time using stack overflow, so I'm so sorry if this is formatted incorrectly in any way. For a comp sci project, I have to do some different things to a 40-item Array List of random numbers.
The task I'm struggling with is this:
Count the longest run of the same number. A run continues only when consecutive numbers
have the same value. The repeated number and the length of the run is then printed. (Ex: Longest run is of number: 3, length is: 5.)
If there is more than one run of maximum length, mark the last one. Print the array with the longest run marked in the following fashion:
1 1 1 6 5 4 6 3 2 3 2 (3 3 3 3 3) 1 5 6 3 4 4 4
I genuinely have no idea how to approach this problem. Even just some pseudocode could be helpful; I know that these should probably be 2 different 'for' loops, one that detects the run and the other that prints it. I have some code from a friend who completed this using Arrays instead of ArrayLists:
public String longestRun()
{
int maxRun=1;
int currentLen = 1;
int repeated = x[0];
for (int i =1; i< 40-1; i++)
{
if (x[i] == x[i+1])
currentLen++;
else
{
if (currentLen >= maxRun)
{
maxRun = currentLen;
repeated = x[i-1];
startRun = i-maxRun;
endRun = i-1;
}
currentLen = 1;
}
}
return "The longest run is " + maxRun + " and the repeated number is " + repeated ;
}
public String printParenth()
{
for(int i = 0; i<40; i++)
{
if(i != startRun+1 && i != endRun+1)
System.out.print(x[i]);
else if(i == startRun+1)
System.out.print("(" + x[i]);
else
System.out.print(x[i] + ")");
}
return "";
}
I know how to create the ArrayList, convert to string & print, etc, it's just this one task that I don't understand. I assume this should be easier with an ArrayList, considering the increased number and utility of ArrayList methods. Thanks so much in advance, I really appreciate it!
Put your numbers in a list or an array.
Set max to 1 (you will always have at least 1 number).
initialize count to 1.
initialize the variable most to the first number in the array
also set the variable last to the first number in the array.
Now iterate thru the list starting with the second number.
If the current number is the same as last, increment count.
then see if count > max.
if it is
set max = count.
set most = last
if it isn't
set count = 1
set last = current number
continue in this fashion until all numbers have been checked.
At the end most will contain the number that was repeated and max will contain the length of the repetition.

updating the array dynamically [duplicate]

This question already has answers here:
How do I remove objects from an array in Java?
(20 answers)
Closed 8 years ago.
I am beginner to java coding, I am facing some complexity in updating the array.
My problem is I have an array named s1[] which consists of 10 elements from that I have to choose 1st 3 elements and I have to store in one array i.e. max1[] array and in next array I have to choose randomly 3 elements from the same array i.e. s1[] and store it in max6[] and I need to do comparison between the two arrays i.e. max1[] and max6[] so that the matching values will be stored.
My code looks like this (here f1 = 3)
for (i1 = 0; i1 < f1; i1++) {
max1[i1] = s1[i1];
System.out.println("1st tree random leaf nodes of phy m/c 1 at tree 1 : " + max1[i1]);
System.out.println(" \n ");
max6[i1] = s1[(int) (Math.random() * f1)];
System.out.println(" random leaf nodes of phy m/c 1 at tree 2: " + max6[i1]);
System.out.println(" \n ");
}
for (int l1 = 0; l1 < f1; l1++) {
for (int k1 = 0; k1 < f1; k1++) {
if (max1[l1] == max6[k1]) {
c1[l1] = max1[l1];
k1++;
System.out.println("the value after crossover is:--------->" + c1[l1]);
break;
}
}
}
now what I want is that I have to repeat the loop for some iterations so that in the next iteration the values of the max1 array in 1st iteration shouldn't be repeated means I have to permanently remove the elements from s1 array until s1 array contains zero elements in it
I have two suggestions for you, it's up to you which you prefer.
Firstly I would suggest converting the array to a list and removing the necessary elements from the list then converting back to the array. Code follows :
List<Double> list = new ArrayList<Double>(Arrays.asList(s1));
list.remove(i1);
s1 = list.toArray(new Double[0]);
Secondly you can shift the specific element of the array to the back and just iterate one position less than the length. This will require you adding an extra int variable to either record the number of elements in the array or to record the amount of deleted elements, the former being the better idea. Code follows :
double temp;
for(int i = 0; i < test.length - 1; i++){
temp = s1[i];
s1[i] = s1[i + 1];
s1[i + 1] = temp;
}
nrE = nrE - 1;
This will require you to have an int nrE with value of the length of the array(here 10) before your first for loop.
Both of these should be implemented inside the for loop at the end of the iteration.
From what I've seen my first suggestion is used most.
Note : I may misunderstand what you are trying to achieve, but I believe your code for getting the 3 random elements is faulty. If f1=3 and you take element at the position Math.random() * f1 you will always get an element in the range 0 to 3. To fix this you can instead use Math.random() * s1.length

Why does this merge sort give incorrect results?

My assignment is to merge two arrays using int arrays that the user fills and we have to assume that there will be a maximum of 10000 inputs from the user, and the user inputs a negative number to stop. Then sort the array from least to greatest and print it out. Initially i thought that this would be quite easy but when i finished, i began getting outputs such as:
Enter the values for the first array, up to 10000 values, enter a negative number to quit: 1
3
5
-1
Enter the values for the second array, up to 10000 values, enter a negative number to quit
2
4
6
-1
First Array:
1
3
5
Second Array:
2
4
6
Merged Array:
6 1 2 3 4 5
as you can see, the six is out of place and i have no idea how to fix it. Here is the source code, i have included copious comments because I really want you guys to help me out to the best of your abilities. IF it's possible to use the same exact technique without implement new techniques and methods into the code please do so. I know there are methods in java that can do all of this in one line but it's for an assignment at a more basic level.
import java.util.Scanner;
public class Merge
{
public static void main(String [] args)
{
Scanner scan = new Scanner(System.in);
int [] first = new int[10000]; //first array, assume 10k inputs max
int [] second = new int[10000]; //first array, assume 10k inputs max
boolean legal = true; //WILL IMPLIMENT LATER
int end = 0; // set how many elements to put in my "both" array
int end2 = 0;// set how many elements to put in my "both" array
System.out.print("Enter the values for the first array, up to 10000 values, enter a negative number to quit");
//get values
for(int i = 0; i<first.length; i++)
{
first[i] = scan.nextInt(); //fill first with user input
if(first[i] <0) //if negative number, stop loop
{
end = i; //get position of end of user input
break;
}
}
System.out.println("Enter the values for the second array, up to 10000 values, enter a negative number to quit");
for(int i = 0; i<second.length; i++) //exact same as the first get values loop
{
second[i] = scan.nextInt();
if(second[i] <0)
{
end2 = i;
break;
}
}
System.out.print("First Array:\n");
for(int i = 0; i<first.length; i++) //print first array
{
if(i == end) //this prevents from printing thousands of zeros, only prints values that user inputed
break;
System.out.println(first[i] + " ");
}
System.out.print("Second Array:\n");
for(int i = 0; i<second.length; i++) //same as printing first array
{
if(i == end2)
break;
System.out.println(second[i] + " ");
}
int [] both = new int[(end)+(end2)]; //instanciate an int array to hold only inputted values from first[] and second[]
int [] bothF = new int[(end)+(end2)]; //this is for my simple sorter algotithm loop
for(int i = 0; i<both.length; i++) //fill both with the first array that was filled
{
both[i] = first[i];
}
int temp = end; // see below
for(int i = 0;i<both.length; i++) //fill array with the second array that was filled(starting from the end of the first array so that the first set is not overwritten
{
if(temp<both.length){ //this prevents an out of bounds
both[temp] = second[i];
temp++;}
}
//simple sorting algorithm
for(int d = both.length -1;d>=0;d--)
{
for(int i = 0; i<both.length; i++)
{
if(both[d]<both[i])
{
bothF[d] = both[d];
both[d] = both[i];
both[i] = bothF[d];
}
}
}
System.out.println("Merged Array:"); //print the results
for(int i = 0; i<both.length; i++)
{
System.out.print(both[i] + " ");
}
//System.out.println("ERROR: Array not in correct order");
}
Your sorting algorithm is faulty.
It's similar to selection sort, in that you take two elements and swap them if they're out of place. However, you don't stop the comparisons when you should: when the index d is less than the index i, the comparison-and-swap based on arr[d] > arr[i] is no longer valid.
The inner loop should terminate with i=d.
The logic of your sort goes something like this:
On the d-th loop, the elements at d+1 and to the right are correctly sorted (the larger numbers). This is true at the beginning, because there are 0 elements correctly sorted to the right of the right-most element.
On each of the outer loops (with the d counter), compare the d-th largest element slot with every unsorted element, and swap if the other element is larger.
This is sufficient to sort the array, but if you begin to compare the d-th largest element slot with already-sorted elements to its right, you'll end up with a larger number in the slot than should be. Therefore, the inner loop should terminate when it reaches d.
Sure, you can do it like this
for (int i = 0; i < end; i++) {
both[i] = first[i];
}
for (int i = 0; i < end2; i++) {
both[i + end] = second[i];
}
// simple sorting algorithm
for (int d = both.length - 1; d >= 0; d--) {
for (int i = 0; i < d; i++) {
if (both[i] > both[d]) {
int t = both[d];
both[d] = both[i];
both[i] = t;
}
}
}
Output(s) -
Enter the values for the first array, up to 10000 values, enter a negative number to quit3
5
-1
Enter the values for the second array, up to 10000 values, enter a negative number to quit
2
4
6
-1
First Array:
3
5
Second Array:
2
4
6
-1
Merged Array:
2 3 4 5 6
First I will start with some recommendations:
1.Give end1 and end2 the initial value as the array lengths.
The printing part - instead of breaking the loop - loop till i == end(if its not changed by the first part it will stay the array length).
One suggestion is to use a "while" statement on the user input to do the reading part (it seems cleaner then breaking the loop- but its OK to do it like you have done too).
Try to use more functions.
now to the main thing- why not to insert the numbers from both arrays to the join array keeping them sorted?
Guiding:
Keep a marker for each array.
Iterate over the new join array If arr1[marker1]> arr2[marker2]
insert arr2[marker2] to the joint array in the current position.
and add 1 to marker2. and the opposite.
(don't forget to choose what happens if the are equal).
This can be achieved because the arrays were sorted in the first place.
Have fun practicing!
I guess you have sort of a reverse "selection sort"-algorithm going on there. I made an class that run your code and printed out the output after every swap. Here is the code which is the same as you got in your application with the addition of print.
for(int d = both.length -1;d>=0;d--)
{
for(int i = 0; i<both.length; i++)
{
if(both[d]<both[i])
{
int temp = both[d];
both[d] = both[i];
both[i] = temp;
printArray(both);
}
}
}
and when we run this on an example array we get this output
[9, 8, 7, 6]=
-> 6879
-> 6789
-> 6798
-> 6978
-> 9678
The algorithm actually had the correct answer after two swaps but then it started shuffling them into wrong order. The issue is the inner for loops end parameter. When you have run the outer loop once, you can be certain that the biggest number is in the end. 'd' is here 3 and it will swap out a bigger number every time it encounters it. the if clause comparisions in the first loop is 6-9 (swap), 9-8, 9-7, 9-9. All good so far.
Potential problems comes in the second iteration with 'd' as 2. Array is now [6,8,7,9] and comparisons are 7-6, 7-8 (swap with result [6,7,8,9]), 8-8, 8-9 (swap!!) resulting in [6,7,9,8]. the last swap was the problematic one. We knew that the biggest number was already in the last spot, but we still compare against it. with every gotrough of the whole inner loop it will always find the biggest number (and all other bigger than both[d] that is already in place) and swap it to some wrong position.
As we know that the biggest number will be last after one iteration of the outer loop, we shouldn't compare against it in the second iteration. You sort of lock the 9 in the array and only try to sort the rest, being in this case [6,8,7] where d = 3, value 7. hence, your inner loop for(int i = 0; i<both.length; i++) becomes for(int i = 0; i<=d; i++). As an added bonus, you know that in the last iteration i==d, and thus the code inside it, if(both[d]<both[i]) will never be true, and you can further enhance the loop into for(int i = 0; i<d; i++).
In your algorithm you always do four comparisons in the inner loop over four iterations of the outer loop, which means there is a total of 16 comparisons. if we use the i<d we'll just do three comparisons in the inner loop on the first iteration of the outer loop, then two, then one. This brings it to a total of six comparisons.
Sorry if too rambling, just wanted to be thorough.

How to get part of array elements by user input using a loop

I am creating a program that takes various double arrays and displays them. The array is 10 elements and I am asked to get the values for elements 2 through 9 from the user input by using a loop. I have tried a for loop but I just don't understand how to get this done.
int c;
for(c = 0; c >= 2 && c <= 9; c++){
System.out.println("Enter a value for the elements 2-9: ");
}
System.out.println(" ");
If you have a Java array as follows:
double myarr[10];
You access elements in an array by index (assuming the array has been populated with data)
double somenum = myarr[3]; // extracts the *fourth* element from the list
To set a value in the array, you use the assignment operator and specify a value:
myarr[7] = 3.14159; // sets the *eighth* element to value '3.14159'
If you wish to iterate over a range of numbers, you can use a for-loop. For-loops have the following format:
for (initialization; condition; increase)
If you wanted to print all numbers between 1 and 10, you can write:
for (int i=1; i<=10; i++) {
System.out.println(i);
}
The trick is to use the variable i in the for-loop and ensure the loop iterates over the proper range. Hint: You can use i as an array index.
Here are some good resources:
Java: Array with loop
http://docs.oracle.com/javase/tutorial/java/nutsandbolts/for.html
http://www.tutorialspoint.com/java/java_loop_control.htm
http://www.homeandlearn.co.uk/java/java_for_loops.html
Here's a loop and a means for user input:
Scanner reader = new Scanner(System.in);
for(int i=2; i<8; i++){
System.out.println("Enter Element "+i);
a=reader.nextInt();
//store "a" somewhere
}
c needs to start at 1 (since you want the second elment) and stop at 8 (for the ninth)
so for(int c=1;c<9;c++) should be the loop
When writing loops remember;
array indexes are 0 based, the first element is at 0, the second at 1 up to the last which is at the length of the array minus 1
if your loop increments, then the smallest value it can have is what ever it starts as, so you shouldn't check to make sure its greater then that, (ie if you start at 2 and increment then you don't need to check to if its greater than or equal to 2 because it always is)
Take a look at the syntax for for loops here
Console console = System.console();
double arr[10];
for(int c = 1; c<10; c++){
String input = console.readLine("Enter a value for the elements 2-9: ");
arr[c] = Double.parseDouble(input);
System.out.println(arr[c]);
}

How to exit the loop with the number 0? but now i have other problems

package hw3;
public class Main {
public static void main(String[] args) {
final int NumberOfElements = 1000;
int[] num = new int[NumberOfElements];
int var = 0;
//create input
java.util.Scanner input = new java.util.Scanner(System.in);
for (int i = 0; i < NumberOfElements; i++) {
System.out.print("Enter any positive number or enter 0 to stop: ");
num[i] = input.nextInt();
var++;
if (num[i] == 0)
break;
}
Arrays.sort( num, 0, var);
int i;
for (i = 0; i < var; i++) {
System.out.print(" " + num[i]);
}
}
}
Write a Java program reading a sequence of positive integers entered one per line. The program stops reading when integer ‘0’ is entered. The program will sort and output them into an ascending numerical order.For example: 5
1
7
12
36
8
0
Output: 1 5 7 8 12 36
Try to understand the problem: there are three steps.
Step 1: Get the input from the user. Continue getting input till the user enters 0
Step 2: Sort
Step 3: Print out the results
Step 1: Your for loop is almost correct.
But the for loop should end immediately after you have got the input.
In the following code,
num[i] = input.nextInt();
var++;
if (num[i] == 0)
break;
you are adding the user input to the array and then checking whether it is 0. This means that the 0 will also be part of your array. If you don't want this, you should check the input and add it to the array only if it is not 0.
Also note the declaration of i before the for loop. Because we need it after the for loop. Why? see below.
int i = 0;
for (i = 0; i < NumberOfElements; i++) {
int n = input.nextInt();
if (n == 0)
break;
else
num[i] = n;
} //for loop ends here
Step 2: Sort it
Arrays.sort(num);
Step 3: Print the output:
for (i = 0; i < num.length; i++) {
System.out.print(" " + num[i]);
}
The problem is, in step 2, an array of 1000 elements is sorted, while you actually need to consider only the number of elements the user has entered. You don't know that initially thats why you created an array of 1000 elements.But, at this point (after step 2) you do know how many number of elements the user has entered. This is present in i
So new step between 1 and 2: Create a new arrays that contains only those elements that the user has entered.
Step 1.5:
int[] newArray = Arrays.copyOf(num, i);
Now sort this new array, and print it (same as your code, but uses the new array we just created)
Arrays.sort(newArray);
for (i = 0; i < newArray.length; i++) {
System.out.print(" " + newArray[i]);
}
Notes:
1. The ideal way to do this is to use Lists and not arrays, but probably since this is homework, you might have to use arrays.
Since this is homework, I don't know whether you are allowed to use Arrays.sort or Arrays.copy. Your professor might frown at this because perhaps his intention was that you learn the constructs of the language via for, if and while. In that case you have to do step 1.5 (make array the right size) and sort by yourself.
This is not difficult (but just remember this is not the best way to do it, except for in a homework)
Copy array (homemade) (in place of step 1.4 above)
int[] newArray = new int[i]
for(int j=0; j<i; j++){
newArray[j] = num[j];
}
Sort (homemade) (in place of step 2 above):
Loop through the elements
If one element is greater than the previous element, swap them (in asc order, the prev element is always lesser or equal to the next element)
There are two loops because you have to do the comparison on a continuous basis: the the first element, compare with the entire array, place it in the right position, take the second compare with the entire array etc...)
for(int j=0; j<newArray.length; j++) {
for(int k=0; k<newArray.length; k++) {
if(newArray[k] > newArray[j]) {
//the swap logic:
int t = newArray[k];
newArray[k] = newArray[j];
newArray[j] = t;
}
}
}
Try to understand what really is happening, instead of just copy pasting.
Once you understand the homemade sort logic, think about this:
The second for loop in the sort or(int k=0; k<newArray.length; k++) { can actually just be for(int k=0; k<newArray.length; k++) {. Why?
Your print loop will remain the way you wrote it, but you will print newArray rather than num. You might want to change the loop variable to int j or something, but i will also work. (i holds the no of inputs now, so I would not use it for any other purpose. But it is just a manner of coding. Technically no difference - the code will work the same way)
I am not combining the parts. I leave that o you, otherwise it will look like I did your homework :-)
num[i] holds the last number you are reading. So you have to compare it against 0 and if it is 0, you have to end the loop. Read about branching statements to find out how to do that.
It is probably also good for you to read about control flow statements in general.
Here your application is reading int, you can check that the last one is != from 0. And break the loop.
If you don't like using break, you can still add a condition to your for.
For sorting an array, there is the Arrays.sort() solution.
And to print them you'll need another loop, but beware as you can have less than 1000 items in your array you can't simply print the whole array.
You'll need to find a way to count the number of elements you added in the array.
After your edit:
Good your application seems to work here is what I got :
Mac-Makkhdyn:~ Makkhdyn$ java hw3.Main
Enter any positive number or enter 0 to stop: 1
Enter any positive number or enter 0 to stop: 2
Enter any positive number or enter 0 to stop: 3
Enter any positive number or enter 0 to stop: 4
Enter any positive number or enter 0 to stop: 5
Enter any positive number or enter 0 to stop: 0
Mac-Makkhdyn:~ Makkhdyn$
The 0 you have must be from somewhere else. Isn't your actual code slightly different from the one you posted here ?
Resources :
javadoc - Arrays.sort()
Java tutorial - The break Statement

Categories

Resources