Not able to add to ArrayList properly - java

I have 2 methods in my program, one to add ***** above and below the smallest int in the array and one to add %%%%% above and below the largest. The method for the largest is essentially the same as the other but for some reason isn't adding what is needed.
Here is the smallest element method:
public static ArrayList smallestElement() {
int smallest = array[0];
for (int i = 0; i < array.length; i++)
if (array[i] < smallest)
smallest = array[i];
String smallestString = String.valueOf(smallest);
ArrayList<String> list = new ArrayList<String>();
for(int i = 0; i < array.length; i++) {
if (smallestString.equals(String.valueOf(array[i]))) {
list.add("*****");
list.add(Integer.toString(array[i]));
list.add("*****");
} else {
list.add(Integer.toString(array[i]));
}
}
return list;
}
Here is the method for the largest element:
public static ArrayList largestElement() {
int largest = array[0];
for (int i = 0; i < array.length; i++)
if (array[i] > largest)
largest = array[i];
String largestString = String.valueOf(largest);
for(int i = 0; i < array.length; i++) {
if (largestString.equals(String.valueOf(array[i]))) {
smallestElement().add("%%%%%");
smallestElement().add(Integer.toString(array[i]));
smallestElement().add("%%%%%");
} else {
smallestElement().add(Integer.toString(array[i]));
}
}
System.out.println(smallestElement());
return smallestElement();
}
}
If anyone knows why this isn't performing correctly, I would really appreciate the help

You are creating a new object every time you are executing the smallestElement function. Instead do something like,
ArrayList<String> list = smallestElement();
Then use this list object every time you are calling smallestElement() method

You have already created the list 3 times over by this line
smallestElement().add("%%%%%");
smallestElement().add(Integer.toString(array[i]));
smallestElement().add("%%%%%");
Create just 1 list and use it instead of calling the smallestelementelement() function multiple times

You are overcomplicating things here. There is no need to turn that minimum array value into a string right there (and to then do String comparisons later on). Btw: those string comparisons are also your problem: your code will definitely not work when your minimal value shows up several times in your array - because your code will put in those patterns for each match!
Instead, you could do something like:
int indexToUse = 0;
for (int i = 0; i < array.length; i++) { // please always use braces!
if (array[i] < array[indexToUse]) {
indexToUse = i;
}
}
List<String> valuesWithMarkerStrings = new ArrayList<>();
for (int i = 0; i < array.length; i++) {
if (i == indexToUse -1 || i == indexToUse+1) {
valuesWithMarkerStrings.add("******");
} else {
valuesWithMarkerStrings.add(Integer.toString(array[i]);
}
}
(where my solution assumes that you want to have *** ... instead of array[i] for such rows ... )

Related

How do I sort an array of integers from minimum to maximum value without using Arrays.sort()?

I'm learning how to use arrays, and I'm trying to manually sort an array of integers using two ArrayList<Integer>.
Here's what I have currently:
public Object[] arraySort (int[] importedArray) {
// !!! This method returns the original imported method (?). !!!
ArrayList<Integer> unsorted = new ArrayList<>();
ArrayList<Integer> sorted = new ArrayList<>();
// Convert importedArray into unsorted Integer ArrayList
for (int i = 0; i < importedArray.length; i++) {
unsorted.add(importedArray[i]);
}
// Find minimum value of unsorted ArrayList, add to sorted ArrayList, and remove min value from unsorted
for (int i = 0; i < unsorted.size(); i++) {
int min = Integer.MAX_VALUE;
int index = 0;
for (int j = 0; j < unsorted.size(); j++) {
if (unsorted.get(j) < min) {
min = unsorted.get(j);
index = j;
}
}
unsorted.remove(index);
sorted.add(min);
}
return unsorted.toArray();
}
However, when I run the method, I get the same imported array back. The first for loop to convert int[] into ArrayList<Integer> apparently worked when I checked using print, so the problem is most likely in the second for loop.
I've also tried other insertion sorting methods, but I'm not sure what I am doing wrong with this type of sorting method. Did I totally screw up somewhere? Or is this method not possible? Thanks in advance for your help!
First of all, you should return the sorted array and not the unsorted one. You should also be careful when using unsorted.size() in the loop header because the programm will call that method every time an iteration has finished. But since you decrease the size inside of the loop with update.remove(index), the size does not stay the same and you just skip some values. Thus, you should save that value in a variable before starting the loop. The following code worked for me:
public Object[] arraySort(int[] importedArray) {
ArrayList<Integer> unsorted = new ArrayList<>();
ArrayList<Integer> sorted = new ArrayList<>();
for (int i = 0; i < importedArray.length; i++) {
unsorted.add(importedArray[i]);
}
int size = unsorted.size();
for (int i = 0; i < size; i++) {
int min = Integer.MAX_VALUE;
int index = 0;
for (int j = 0; j < unsorted.size(); j++) {
if (unsorted.get(j) < min) {
min = unsorted.get(j);
index = j;
}
}
unsorted.remove(index);
sorted.add(min);
}
return sorted.toArray();
}

How do I remove the item with the highest value in an unsorted array?

So right now I am trying to code a function that will remove the highest value in an unsorted array.
Currently the code looks like this:
#Override
public void remove() throws QueueUnderflowException {
if (isEmpty()) {
throw new QueueUnderflowException();
} else {
int priority = 0;
for (int i = 1; i < tailIndex; i++) {
while (i > 0 && ((PriorityItem<T>) storage[i - 1]).getPriority() < priority)
storage[i] = storage[i + 1];
i = i - 1;
}
/*int max = array.get(0);
for (int i = 1; i < array.length; i++) {
if (array.get(i) > max) {
max = array.get(i);
}*/
}
tailIndex = tailIndex - 1;
}
Here I have my attempt at this:
int priority = 0;
for (int i = 1; i < tailIndex; i++) {
while (i > 0 && ((PriorityItem<T>) storage[i - 1]).getPriority() < priority)
storage[i] = storage[i + 1];
i = i - 1;
The program runs no bother but still deletes the first item in the array instead of the highest number. This code was given my my college lecturer for a different solution but unfortunately it doesn't work here.
Would this solution work with enough altercations? Or is there another solution I should try?
Thanks.
The code snippet in the question can be updated to below code, while keeping the same data structure i.e. queue and this updated code has 3 steps - finding the index of largest element, shifting the elements to overwrite the largest element and finally set the tailIndex to one less i.e. decrease the size of the queue.
#Override
public void remove() throws QueueUnderflowException {
if (isEmpty()) {
throw new QueueUnderflowException();
} else {
int priority = 0;
int largeIndex = 0;
for (int i = 0; i < tailIndex; i++) {
if (((PriorityItem<T>) storage[i]).getPriority() > priority) {
priority = ((PriorityItem<T>) storage[i]).getPriority();
largeIndex = i ;
}
}
for(int i = largeIndex; i < (tailIndex - 1) ; i++)
storage[i] = storage[i + 1];
}
tailIndex = tailIndex - 1;
}
Hope it helps.
Step 1
Find the highest index.
int[] array;
int highIndex = 0;
for (int i = 1; i < highIndex.size(); i++)
if (array[highIndex] < array[highIndex])
highIndex = i;
Step 2
Create new array with new int[array.size() - 1]
Step 3
Move all values of array into new array (except the highest one).
My hint: When its possible, then use a List. It reduces your complexity.
You can find the largest Number and it's index then copy each number to its preceding number. After that, you have two options:
Either add Length - 1 each time you iterate the array.
Or copy the previous array and don't include removed number in it.
Working Code:
import java.util.Arrays;
public class stackLargest
{
public static void main(String[] args)
{
int[] unsortedArray = {1,54,21,63,85,0,14,78,65,21,47,96,54,52};
int largestNumber = unsortedArray[0];
int removeIndex = 0;
// getting the largest number and its index
for(int i =0; i<unsortedArray.length;i++)
{
if(unsortedArray[i] > largestNumber)
{
largestNumber = unsortedArray[i];
removeIndex = i;
}
}
//removing the largest number
for(int i = removeIndex; i < unsortedArray.length -1; i++)
unsortedArray[i] = unsortedArray[i + 1];
// now you have two options either you can iterate one less than the array's size
// as we have deleted one element
// or you can copy the array to a new array and dont have to add " length - 1" when iterating through the array
// I am doing both at once, what you lke you can do
int[] removedArray = new int[unsortedArray.length-1];
for(int i =0; i<unsortedArray.length-1;i++)
{
System.out.printf(unsortedArray[i] + " ");
removedArray[i] = unsortedArray[i];
}
}
}
Note: Use List whenever possible, it will not only reduce complexity, but, comes with a very rich methods that will help you a big deal.

Java - iterate through ArrayList for only increasing elements

Here is my ArrayList:
[1,2,1,0,3,4]
I'm trying to return this:
[1,2,3,4]
Here is my current attempt:
for (int i = 0; i < myArray.size() - 1; i++) {
if (myArray.get(i) < myArray.get(i + 1)) {
System.out.println("Increasing sequence...");
}
}
However, this is not returning the desired output, any ideas?
You'll have to maintain an index (or value) of the last element that you had printed and store it in some variable. Then, you'll have to use the stored element for every new element and check if is greater than the stored element.
As you have mentioned, the first element has to be anyway printed, no matter what.
Something like this might work:
List<Integer> myArray = Arrays.asList(new Integer[]{1,2,1,0,3,4});
System.out.println(myArray.get(0));
int prevPrint = myArray.get(0);
for (int i = 1; i < myArray.size();i++) {
if (myArray.get(i) > prevPrint) {
System.out.println(myArray.get(i));
prevPrint = myArray.get(i);
}
}
The reason why your program was failing was because you were comparing the adjacent two values only and it was possible that you might have already printed a value which is greater than any of the two adjacent values.
A similar question, but a totally different approach (LIS) exists and can be found here
A slight variant on Parijat's answer to avoid repeating the System.out.println:
for (int j = 0; j < myArray.size();) {
System.out.println(myArray.get(j));
int start = j;
do {
++j;
while (j < myArray.size() && myArray.get(j) <= myArray.get(start));
}
Try this,
public static List<Integer> findIncreasingOrder(int[] nums) {
List<Integer> result = new ArrayList<>();
int MAX = Integer.MIN_VALUE;
for (int i = 0; i < nums.length; i++) {
int value = nums[i];
if (value >MAX){
System.out.println(value);
MAX = value;
result.add(value);
}
}
return result;
}

Java for loop needs to pick up where it left off

I need the second for loop to pick up where it left off. Every time the if statement is true I need a slot to fill in the array used in the first for loop. But I don't want the same key value to keep getting added. I need the second for loop to move to the next key value. (In the code below, arrl is an ArrayList of objects that have a value)
int temp = 0;
int count = 0;
for(int i = 0; i < eeVal.length; i++)
{
count= 0;
for(int j = temp; j < arrl.size(); j++)
{
if(arrl.get(j).getValue() == 1 && count == 0)
{
eeVal[i] = arrl.get(j);
count++;
temp=j;
}
}
}
}
return eeVal;
You need another variable to track where the inside loop has gotten to. Something like the following:
int temp = 0;
for(int i = 0; i < eeVal.length; i++)
{
for(int j = temp; j < arrl.size(); j++)
{
if(arrl.get(j).getValue() == 1)
{
eeVal[i] = arrl.get(j);
}
temp=j;
}
}
}
return eeVal;
This way, once the outside loop runs the second time around, the inside loop will start from 'temp' until the end of the loop.
From your explanation, it sounds like you do not want the inner for loop. The traversal of arrl needs to be manually controlled using a variable, e.g.`cnt', which only gets incremented when your condition for incrementing it is satisfied.
What you probably are looking for is a List.
In your answer, you don't need the first loop. This one has issues though - index i can go out of bounds.
int i = 0;
for(int j = 0; j < arrl.size(); j++) {
if(arrl.get(j).getValue() == 1) {
eeVal[i++] = arrl.get(j);
}
}
return eeVal;
What you need is a dynamic collections such as List.
Using list (I am calling the type as MyType).
List<MyType> vals = new ArrayList<>();
for(MyType item : arrl) {
if(item.getValue() == 1) {
vals.add(arrl.get(j));
}
}
return vals.toArray(new MyType[vals.size()]);
The code was picking up where the last correct value was. I needed to add 1 to j when I wanted progress to know where I left off.
int count2 = 0;
int progress = 0;
for(int i = 0; i < retVal[h].length; i++)
{
count2 = 0;
for(int j = progress; j < arr.size(); j++)
{
if(arr.get(j).getLevel() == h && count2==0)
{
retVal[h][i] = arr.get(j);
count2++;
progress = j+1;
}
}
}
return retVal;

Specific comparison of two arrays in java

There are many symbol games working in this way so this should sound familiar to you.
Facts:
I have two arrays with same length of 4.
(A[4] and B[4])
I fill them with random integers from 1 to 6.
I can NOT sort them in any way (they must stay the same).
Problems:
I need to compare them and after that I need to have 3 values. FIRST one needs to count how many elements are the same and in the same place. I do it like this and it is working:
int first = 0;
int k = 0;
for (int j=1; j<=4; j++)
{
k++;
if (A[k] == B[j])
{
first++;
}
}
SECOND one needs to count how many elements are the same BUT not at the same place. THIRD one needs to count how many elements are not the same at all.
I need a solution to count either SECOND or THIRD number, because after that I can just subtract like 4-(first+second) or 4-(first+second).
Here's the logic you should use: loop over the first array; for each element, check if the corresponding element of the second array is the same - if yes, increment your first counter. If they are not the same, then check whether the second array contains the corresponding element of the first array. If it does, then it's definitely not in the same position (you just checked same positions) - increment your second count. Otherwise, increment your third count. The code can be as following:
int[] A = {...};
int[] B = {...};
List<Integer> lstB = new ArrayList<Integer>(B.length);
for (int index = 0; index < B.length; index++) {
lstB.add(B[index]);
}
int first = 0, second = 0, third = 0;
for(int i=0; i<4; i++) {
if(A[i] == B[i]) {
first++;
}
else if(lstB.contains(A[i]) {
second++;
}
else {
third++;
}
}
SOLUTION
Eventually I made the right algorithm. In general, the solution is to keep track of what fields you used when counting FIRST value. And here is the code:
int first = 0;
int second = 0;
int third = 0;
boolean[] codeUsed = new boolean[4];
boolean[] guessUsed = new boolean[4];
//same value and same place
for (int i = 0; i < 4; i++)
{
if (A[i] == B[i])
{
first++;
codeUsed[i] = guessUsed[i] = true;
}
}
//same value but not right place
for (int i = 0; i < 4; i++)
{
for (int j = 0; j < 4; j++)
{
if (!codeUsed[i] && !guessUsed[j] && A[i] == B[j])
{
second++;
codeUsed[i] = guessUsed[j] = true;
break;
}
}
}
//not the same value
third = 4 - first - second;

Categories