Java - iterate through ArrayList for only increasing elements - java

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

Related

A method for counting unique elements in a array with loop (Java)

I'm trying to make a method that counts the number of unique elements in an array. For example, if the array contains [1,2,3,4,5,1,5] there are 3 unique elements and my method should return the number 3.
This is what I´ve got so far:
static int numberOfUniqueIntegers(int[] number, int len) {
int unique = 0;
for (int i = 0; i < len; i++){
int j;
for (j = 0; j < i; j ++) {
if (number[i] == number[j]) {
break;
}
}
if (i == j);
unique++;
}
return unique;
}
The method takes in the array number and an integer len (which is the length of the array).
But in this case: [1,2,3,4,5,1,5] my method would return 5, instead of 3. I somehow need to check if the number has been repeated before, and if not unique++.
You can create a frequency Map and then get the number of keys that have only one occurrence.
static int numberOfUniqueIntegers(int[] number) {
Map<Integer, Long> freq = Arrays.stream(number).boxed().collect(
Collectors.groupingBy(x -> x, Collectors.counting()));
return (int) freq.entrySet().stream().filter(e -> e.getValue().equals(1L))
.map(Map.Entry::getKey).count();
}
Demo
This one should work, just retain the elements already seen in a separate array :
static int numberOfUniqueIntegers(int[] number, int len) {
int unique = 0;
List<Integer> temp = new ArrayList<>();
for (int i = 0; i < len; i++){
if (!temp.contains(number[i]))
{
unique ++;
temp.add(number[i]);
}
}
return unique;
}
static int numberOfUniqueIntegers(int[] number, int len) {
int unique = 0;
boolean isRepeated;
for (int i = 0; i < len; i++){
isRepeated = false;//setting to defalut value
int j;
for (j = 0; j < len; j ++) {
if(j == i) continue;
if (number[i] == number[j]) {
isRepeated = true;//if caught duplicate
break;
}
}
//if not caught duplicate then increment unique ++
if(!isRepeated) unique++;
}
return unique;
}
What wen wrong?
You have to match every value with everyother value which you did not as because you are just using an array and there is no way to figure if futures values had a match in past. So, you have to cover the length of array and check each value against every value in it. if it was to be written using java collections then it be would much simpler and with less time complexity
If you need to do this without using any additional space, e.g. a Set, then you have no option but to compare each element in the array against all others, an O(n^2) solution.
static int numberOfUniqueIntegers(int[] number, int len)
{
int unique = 0;
for (int i = 0; i < len; i++)
{
int j = 0;
for (; j < len; j++)
if (i != j && number[i] == number[j]) break;
if (j == len) unique++;
}
return unique;
}
If you can use additional space then are options that use a Set.
You can try this with O(2n) complexity
static int numberOfUniqueIntegers() {
//int[] abc = { 1, 2, 3, 4, 5, 1, 5 };
int[] abc = { 1, 1, 1 };
Map<Integer, Integer> st = new HashMap();
int unique = 0;
for (int i = 0; i < abc.length; i++) {
if (st.isEmpty() || st.containsKey(abc[i])) {
Integer vl = st.get(abc[i]);
st.put(abc[i], Objects.nonNull(vl) ? (vl + 1) : 1);
} else {
st.put(abc[i], 1);
}
}
for (int i : st.keySet()) {
if (st.get(i) == 1) {
unique = unique + 1;
}
}
System.out.println(st);
return unique;
}
The easiest way is to just use Set.
int[] s = { 1, 2, 1, 5, 3, 4, 5, 1, 1, 5 };
int count = numberOfUniqueIntegers(s);
System.out.println("Count = " + count);
Prints
Count = 3
Set#add returns false if element exists, true otherwise
if seen doesn't contain it, add to unique.
if it has already been seen, remove from unique.
only the unique ones will remain.
static int numberOfUniqueIntegers(int[] number) {
Set<Integer> seen = new HashSet<>();
Set<Integer> unique = new HashSet<>();
for (int i : number) {
if (!seen.add(i)) {
unique.remove(i);
continue;
}
unique.add(i);
}
return unique.size();
}
Due to the nature of Set the above works in O(n) and no explicit counting of elements needs to be done.
Normally asking questions like this, many stack overflow answers will give you solutions, however, that might not be conducive to working through the problem yourself.
Keep in mind there are multiple ways to solve this kind of problem.
Use a Set (a data structure to deal specifically to deal with uniques)
Sort and count. On duplicates, move on.
Just want to point out a potential issue with your code. You are using a terminator on your conditional clause if(i == j);
Your code will compile and run correctly, however it will simply check the comparison and run count++ every time. You will want to fix this clause.
The correct syntax should be
if (i == j) {
count++
}
Check comment for the exact lines:
static int numberOfUniqueIntegers(int[] number, int len) {
int unique = 0;
for (int i = 0; i < len; i++){
int j;
for (j = 0; j < i; j ++) {
if (number[i] == number[j]) {
break;
}
}
if (i == j); // This comparison is always ignored.
unique++; // This line is always happening
}
return unique;
}
You can use set
public static int numberOfUniqueIntegers(int[] number, int len) {
Set<Integer> st = new HashSet();
int unique = 0;
for (int i = 0; i < len; i++) {
if (!st.add(number[i])) {
unique = unique - 1;
} else {
unique = unique + 1;
}
}
return unique;
}

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.

Not able to add to ArrayList properly

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 ... )

How to remove an Integer from an Array Java

I am a newbie in Java programming and I have a trouble in my program.
I have an array and i want to extract the max integer from it and return it to the main program. But without using ArrayList.
I must not have 0 in this certain position when i print it so I cant just replace it. Take a look at what i did so far but i think that it is so wrong.
public int extractMax()
{
for (int i = 0; i < size; i++)
{
if(maxInsert == Queue[i])
{
Queue[i] = null;
return maxInsert;
}
} return -1;
}
You cannot assign null if the array in a an array of primitives, you would see an error like this :
cannot convert from null to int
If the array is an array of objects (Integer for example), then assigning it to null would work, but I would suggest if you need to manipulate the entries of your array that you use a List instead.
For example :
List<Integer> integers = new ArrayList<>(Arrays.asList(new Integer[]{1,2,3,4,5,6,7,8,9,10}));
System.out.println(integers.size());
integers.remove(new Integer(3));
System.out.println(integers.size());
Would print :
10
9
So the logic here is to basically iterate through every element of the array to see if there is an element greater than the current greatest element (starts at the first element) in the array. If a greater element is found, then the max variable is reset to this new value and the loop carries on. If an even greater element is found, then the same thing happens by updating the max variable. To actually remove this element from the array, you can create a new array with a size of one less than the original size, copy all the elements up to the max into the new array, and shift all the elements to the right of the max by to the left by one. This is what it should look like.
public int extractMax()
{
maxInsert = Queue[0];
int maxIndex = 0;
for (int i = 1; i < size; i++)//get the location of the max element
{
if(maxInsert < Queue[i])
{
maxInsert = Queue[i];
maxIndex = i;
}
}
int[] temp = new int[Queue.length - 1];
for(int j = 0; j < maxIndex; j++){ //adding elements up until the max
temp[j] = Queue[j];
}
for(int k = maxIndex; k < temp.length; k++){ //adding elements after the max
temp[k] = Queue[k+1];
}
Queue = temp; //queue is now this new array we've just made
return maxInsert;
}
Basically you can not remove an element from an Array like in List objects. So create a new Array and add all elements in Queue except the bigger one to the new Array. And lastly, assign the new array to the Queue. Here is an example code:
public int extractMax()
{
for (int i = 0; i < size; i++)
{
if(maxInsert == Queue[i])
{
removeFromArray(i);
return maxInsert;
}
} return -1;
}
private void removeFromArray(int i) {
int[] newQueue = new int[Queue.length-1];
int k = 0;
for (int j = 0; j < newQueue.length; j++,k++) {
if(i == j) {
k++;
}
newQueue[j] = Queue[k];
}
Queue = newQueue;
}

Removing duplicate strings from an array?

How can I remove duplicate strings from a string array without using a HashSet?
I try to use loops, but the words not delete.
StringBuffer outString = new StringBuffer("Our, aim, and, isn't, easy, you, you're, actual, and, are, aren't, and, improve, achieving, and, Obviously, and, illumination, are");
wordList = outString.toString().split(", ");
for (i = 0; i < wordList.length; i++) {
for (j = 0; j < wordList.length; j++) {
if((wordList[i]!=wordList[j])&&(j>i)){
t=true;
}
}
if(t==true){
k++;
}
}
String[] wordList1 = new String[k];
wordList = outString.toString().split(", ");
for (i = 0; i < wordList.length; i++) {
(j = 0; j < wordList.length; j++) {
if((wordList[i]!=wordList[j])&&(j>i)){
t=true;
}
}
if(t==true){
wordList1[i]=wordList[i];
}
}
1)
I think you need to use the equals operator. Try
if (!wordList[i].equals(wordList[j])){
instead of !=.
2) Also Kevin is right. You need to set t back to false.
3) Side note as pointed out by others already: To be more efficient you should start the inner loop with
for (j = i+1; j < wordList.length; j++) {
4) Another side note: Your result array is still too long. If you don't want to use a List<String> and it is ok to loose the original array you could go with a solution as suggested by Zim-Zam O'Pootertoot and set the original duplicates to null, add a counter
to count how many null values you assigned, initialize the new array with the correct size and loop a final time over the first array and copy only the non-null values into your new array.
Try this code to remove dup words:
StringBuilder sb = new StringBuilder();
for (int i = 0; i < wordList.length; i++) {
boolean found = false;
for (int j = i+1; j < wordList.length; j++) {
if (wordList[j].equals(wordList[i])) {
found = true;
break;
}
}
// System.out.printf("Checking: [%s]%n", wordList[i]);
if (!found) {
if (sb.length() > 0)
sb.append(' ');
sb.append(wordList[i]);
}
}
System.out.printf("Unique: [%s]%n", sb);
If you are allowed to use Lists, you can define a generic method that does this fairly easily:
public <T> T[] removeDuplicates(final T[] array) {
List<T> noDuplicates = new ArrayList<T>();
for (T arrayElem : array) {
if (!noDuplicates.contains(arrayElem)) {
noDuplicates.add(arrayElem);
}
}
return (T[]) noDuplicates.toArray();
}
You probably want to set t back to false after pulling the value you want:
if(t)
{
wordList1[i]=wordList[i];
t = false;
}
Also this:
if((wordList[i]!=wordList[j])&&(j>i))
Will always return true since strings are immutable (unless you compared a string to an exact reference of itself which you disallow with j>i). You need to change it to say this:
if (!(wordList[i].equals(wordList[j]))&&(j>i))
Using .equals will compared that they contain the same string, not that they point to the exact reference of a string.
Not sure if that's the only problems or not, a bit unclear from what's given.
In your inner loop, initialize j = i + 1
if(wordlist[i] != null && wordlist[i].equals(worldlist[j])) { wordlist[j] = null; }
...and then compact the array when you're finished to remove all null values
How about using a List:
wordList = outString.toString().split(", ");
List<String> finalList = new ArrayList<String>();
for(String val : wordList) {
if(!finalList.contains(val)) {
finalList.add(val);
}
}
A Set would be more efficient, however. If you can't use a List or a Set, and you are forced to remove the duplicates, then you will have to loop through the array each time, which will perform horribly.
Iterate through the array, and store in an auxiliary int[] or List<Integer> the indexes of duplicates that you find with your two for's.
Create a new Array, with size equal to the original one minus the size of the repeated Strings.
Iterate through your original array, if the index isn't on your auxiliary list, set it to your new Array.
The best and most effective method is to suppose arr is the array that contains strings and can have duplicate values:
Arrays.sort(arr);
int l = 0;
for (int a = 0; a < arr.length; a++) {
if (a == arr.length - 1)
l++;// its a unique value
else if (!(a[a + 1].equals(arr[a])))
l++;// its also a unique
}
String newArray[] = new String[l];
l = 0;
for (int a = 0; a < arr.length; a++) {
if (a == arr.length - 1)
newArray[l] = arr[a];
else if (!(a[a + 1].equals(arr[a]))) {
newArray[l] = arr[a];
l++;
}
}
Try this...
public class RemoveDupsStringArray {
public static void main(String[] args) {
String[] withDuplicates = new String[] {"one","one","two","three","one","three","three"};
String[] withoutDuplicates = new String[] {"one","two","three"};
removeDuplicates(withDuplicates);
removeDuplicates(withoutDuplicates);
}
private static void removeDuplicates(String[] array) {
int[] occurence = new int[array.length];
for (int i = 0; i < array.length; i++) {
for(int j=i+1;j<array.length;j++){
if(array[i]==array[j]){
occurence[j]=j;
}
}
}
int resultLength=0;
for(int i=0;i<occurence.length;i++){
if(occurence[i]==0){
resultLength++;
}
}
String[] result=new String[resultLength];
int index=0;int j=0;
for(int i=0;i<occurence.length;i++){
index = occurence[i];
if(index==0){
result[j]= array[i];
j++;
}
}
for(String eachString : result){
System.out.println(eachString);
}
}
}

Categories