Insert Element between each List element - java

Is there a better way to insert an Element between each pair of elements into a List in Java than iterating through it
List<Integer> exampleInts = new ArrayList<>(Arrays.asList(1,2,3,5,8,13,21));
for (int i = 1; i < exampleInts.size(); i++) {
int delimiter = 0;
exampleInts.add(i, delimiter);
i++;
}

No, there is no ready utils for this in standard java libraries.
BTW, your loop is incorrect and will work infinitely until memory end. You should increment i variable one more time:
for (int i = 1; i < exampleInts.size(); i++) {
int delimiter = 0;
exampleInts.add(i, delimiter);
i++;
}
or change loop conditions to for (int i = 1; i < exampleInts.size(); i+=2) {

Try this solution it is working correctly.
List<Integer> exampleInts = new ArrayList<>(Arrays.asList(1, 2, 3, 5,
8, 13, 21));
int size = (exampleInts.size()-1)*2;
for (int i = 0; i < size; i+=2) {
int delimiter = 0;
exampleInts.add(i+1, delimiter);
}
System.out.println(exampleInts);

Related

Array method printing is almost right, just one value is off which I'm not sure why

So I'm trying to get an array to be passed into a separate method and then return a new sized array but the program has just one incorrect value. For example, I have an array
int [] myInches = {89,12,33,7,72,42,76,49,69,85,61,23};
That I'm trying to pass into my createLowerArray method
public static int [] createLowerArray(int maxParam, int [] myInchesParam) {
int [] betterInches = {0,0,0,0,0,0,0,0,0,0};
int count = 0;
for (int i = 0; i < myInchesParam.length; i++) {
if (myInchesParam[i] < maxParam) {
count++;
}
betterInches = new int [count];
int newCount = 0;
for (int q = 0; q < betterInches.length; q++) {
if (myInchesParam[newCount] < maxParam) {
betterInches[q] = myInchesParam[newCount];
}
newCount++;
}
}
return betterInches;
}
With maxParam just being whatever the user inputs. So let's say they put in 40, the second method will see that only 4 elements, (12,33,7, and 23) are less than 40 and create an array of length 4 with position 0 being 12, [1] = 33, [2] = 7, and [3] = 23, but for some reason my program makes it so. Position 0 in the new array is 0, [1] = 12, [2] = 33, and [3] = 7. the length is correct but the values aren't in the right positions. I got help with this earlier and thought I had it, it feels bad to be back so fast but I just can't seem to figure it out. Thank you to anyone who helps. I know this can be made easier with lists, streams and the like but I need practice with loops.
Expected output should be
int length = 4
[0] = 12
[1] = 33
[2] = 7
[3] = 23
Current output is
int length = 4
[0] = 0
[1] = 12
[2] = 33
[3] = 7
The immediate problem is here:
for (int q = 0; q < betterInches.length; q++) {
if (myInchesParam[newCount] < maxParam) {
betterInches[q] = myInchesParam[newCount];
}
newCount++;
}
You are always incrementing newCount, even if you didn't copy the value. Also, you need to loop over myInchesParam, not betterInches:
for (int j = 0, q = 0; j < myInchesParam.length; j++) {
if (myInchesParam[j] < maxParam) {
betterInches[q] = myInchesParam[j];
q++;
}
}
Additionally, you are doing a lot more work than necessary - your current code is quadratic in the size of the input array. You create the new betterInches array on each iteration of the outer loop, and then discard that and create it again on the next iteration.
Move the inner loop out of the outer loop:
for (int i = 0; i < myInchesParam.length; i++) {
if (myInchesParam[i] < maxParam) {
count++;
}
}
betterInches = new int [count];
for (int i = 0, q = 0; i < myInchesParam.length; i++) {
if (myInchesParam[i] < maxParam) {
betterInches[q++] = myInchesParam[i];
}
}
Try this
for (int q = 0; q < betterInches.length; q++) {
if (myInchesParam[q] < maxParam) {
betterInches[newCount] = myInchesParam[q];
newCount++;
}
}
Updated
Actually you are not iterating on whole array for getting your params. changed second loop to this.
int newCount = 0;
for (int q = 0; q < myInchesParam.length; q++) {
if (myInchesParam[q] < maxParam) {
betterInches[newCount] = myInchesParam[q];
newCount++;
}
}
seprate first loop and second loop. your second loop is inside the first loop. take a look on code below.
public static int [] createLowerArray(int maxParam, int [] myInchesParam) {
int [] betterInches = {0,0,0,0,0,0,0,0,0,0};// Dont need to initialize
int count = 0;
for (int i = 0; i < myInchesParam.length; i++) {
if (myInchesParam[i] < maxParam) {
count++;
}
} // First loop end here
betterInches = new int [count];
int newCount = 0;
for (int q = 0; q < myInchesParam.length; q++) {
if (myInchesParam[q] < maxParam) {
betterInches[newCount] = myInchesParam[q];
newCount++;
}
} // Second Loop ends heer
return betterInches;
}

Java Removing Redundant Items in Array

For this particular problem I am attempting to remove redundant elements in an sorted array and replace them all with 0s at the end of the array. For example, if I had an array consisting of the int elements
1,3,3,4,4,5,6,6,7
My output array should be
1,3,4,5,6,7,0,0,0
My first attempt at the problem was to create a swapper in order to push all the 0s to the end of the list after removing the elements, but it won't seem to push the zeros to the end of the list. Here is my code.
public void implode(int[] ary)
{
int swapper = -1;
int[] newARY = new int[ary.length];
int current = -1;
for (int i = 0; i < ary.length; i++)
{
if (current != ary[i])
{
newARY[i] = ary[i];
current = ary[i];
}
}
for (int i = 0; i < ary.length; i++)
{
if (ary[i] == 0)
{
if (ary[i + 1] != 0)
{
swapper = ary[i + 1];
ary[i] = swapper;
ary[i + 1] = 0;
}
}
}
ary = newARY;
for (int i = 0; i < newARY.length; i++)
{
System.out.print(newARY[i] + " ");
}
}
The array im testing it with is,
int[] aryIn2 = {1, 1, 2, 3, 4, 4, 5, 6};
However, when outputting the imploded array, I receive this one.
1 0 2 3 4 0 5 6
Is there something I am missing?
Thanks in advance.
not an answer to your problem, but using (if possible) java streams can shorten your way:
int[] arr = {1,3,3,4,4,5,6,6,7};
// distinct
List<Integer> list = Arrays.stream(arr).distinct().boxed().collect(Collectors.toList());
// pad with zero's
while(list.size() < arr.length) {
list.add(0);
}
// display
System.out.println(list.stream().map(String::valueOf).collect(Collectors.joining(",")));
will output
1,3,4,5,6,7,0,0,0
Two issue with you code that I observed.
1) Your swapper logic is performing swapping on a different array than the one in which you had done modification earlier
2) You need to have this logic in a bubble-sort way, i.e. loop inside a loop
Below is a working modified sample code of your method. I have modified only the second for-loop logic
public void implode(int[] ary) {
int swapper = -1;
int[] newARY = new int[ary.length];
int current = -1;
for (int i = 0; i < ary.length; i++) {
if (current != ary[i]) {
newARY[i] = ary[i];
current = ary[i];
}
}
for (int i = 0; i < newARY.length - 1; i++) {
if (newARY[i] == 0 && newARY[i + 1] != 0) {
for (int j = i; (j + 1) < newARY.length; j++) {
swapper = newARY[j + 1];
newARY[j] = swapper;
newARY[j + 1] = 0;
}
}
}
for (int i = 0; i < newARY.length; i++) {
System.out.print(newARY[i] + " ");
}
}
In this first loop:
for (int i = 0; i < ary.length; i++) {
if (current != ary[i]) {
newARY[i] = ary[i];
current = ary[i];
}
}
You fill newARY with elements in ary with duplicated value turns to 0:
newARY: 1 0 2 3 4 0 5 6
However, in the second loop:
for (int i = 0; i < ary.length; i++)
{
if (ary[i] == 0)
{
if (ary[i + 1] != 0)
{
swapper = ary[i + 1];
ary[i] = swapper;
ary[i + 1] = 0;
}
}
}
You're modifying your original ary array. So the newARY is not updated.
However, your attempt to push 0 to the end of array also fail if there are more than two 0s consecutive. And it is also vulnerable to ArrayOutOfBoundIndexException since you try to read ary[i+1] without restriction on i
One simple and straight forward way to push 0s to the end of the array is to create new array with non-0s elements and fill 0s later:
int[] result = new int[ary.lenght];
int resultIndex = 0;
for (int i = 0; i < newARY.length; i++) {
if (newARY[i] != 0) {
result[resultIndex++] = newAry[i];
}
}
for (int i = resultIndex; i < newARY.length; i++) {
result[i] = 0;
}
// Print result array
Hint: Using above strategy, you can simplify your code. No need to create immediate array newARY. Just loop over the original array, push unique elements to the result array, then fill any slot left with 0s.

A very long(unknown size) int array of positive integers, separated by negatives. How to reverse these positive subarrays linear time?

Suppose we have a stream of int array of positive and negative integers.I want to use negative numbers as separators, and reverse the positive subarrays. for instance [1, 2, 3, 4, -5, 6, 7, 8, -9, ...] becomes [4,3,2,1,-5, 8, 7, 6, -9, ...]
I'm trying to come up with a linear (and possibly in place) solution but i can't.
Loop into your array while testing for negatif numbers.
Creates arrays 0f integer and use Collections.reverse() on the arrays created.
ArrayList<ArrayList<Integer>> lists = ArrayList<ArrayList<Integer>>();
int subCounter=0;
lists.add(new ArrayList<Integer>());
for(int i=0; i originalArray.length; i++){
(if originalArry[i] < 0){
lists.add(new ArrayList<Integer>());
subCounter++;
}
else{
lists.get(subCounter).add(originalArry[i]);
}
}
int[] newArray = new int[oroginalArray.length];
int counter = 0;
for(ArrayList<Integer> list : lists){
Collections.reverse(list);
for(int i=0; i < list.size(); i++){
newArray[counter] = list.get(i);
counter++;
}
newArray[counter] = originalArray[counter]; // add the separator
counter++;
}
It may need debugging but the philosophy is there.
This works. I just tested it. (short and sweet)
int[] array = new int[]{1,2,3,4,-5,6,7,8,-9,10,-11,12,13,14,15};
ArrayList<Integer> positives = new ArrayList<Integer>();
ArrayList<Integer> preFinalArray = new ArrayList<Integer>();
for(int i: array){
if(i>0) positives.add(new Integer(i));
else{
for(int j = positives.size()-1; j>=0; j--) preFinalArray.add(positives.get(j));
preFinalArray.add(new Integer(i));
positives.clear();
}
}
if(positives.size()>0) for(int i = positives.size()-1; i>=0; i--) preFinalArray.add(new Integer(positives.get(i)));
int[] newArray = new int[preFinalArray.size()];
for(int i = 0; i < newArray.length; i++) newArray[i]=preFinalArray.get(i).intValue();
for(int i: newArray)System.out.println(i);
I didn't try this code, but it should work:
public int[] convert(int[] c){
int[] ret = new int[c.length];
ArrayList<Integer> rev = new ArrayList<>();
for(int i = 0; i<c.length; i++){
if(c[i]>=0){
//If the number is positive, schedule it to be reversed
ret.add(i);
}else{
//If the number is negative, add the array reversed
//and then the number itself
int s = rev.size();
for(int y = 0; y<s; y++){
ret[i-1-y] = rev.get(y);
}
//Recreate the list to clear the scheduled content
rev = new ArrayList<>();
ret[i] = c[i];
}
}
//Flush the end of the array
int s = rev.size();
for(int y = 0; y<s; y++){
ret[c.length-1-y] = rev.get(y);
}
}

Java Logical Array Trouble

I am trying to make an Array so that it contains 10 different integers 0-9.
I have this:
for (int i = 0; i < perm.length; i++)
{
int num = (int) (Math.random() * 9);
boolean check = true;
if (Arrays.asList(perm).contains(num) == true)
check = false;
else
{
check = true;
perm[i] = num;
}
while (check == false)
{
num = (int) (Math.random() * 9);
}
}
It seems that it should work and make an array with different integers, but it does not.
If you want to avoid creating a List you can just shuffle yourself :
Random random = new Random();
int[] perm = new int[10];
for (int i = 0; i < 10; i++) {
perm[i] = i;
}
for (int i = 0; i < 9; i++) {
int j = random.nextInt(10 - i);
int tmp = perm[i];
perm[i] = perm[i + j];
perm[i + j] = tmp;
}
System.out.println(Arrays.toString(perm));
How about this instead (if you want a more concise approach):
List<Integer> l = new ArrayList<Integer>();
for (int i = 0; i < 10; i++)
l.add(i); // add 0-9
Collections.shuffle(l)
Integer[] ints = l.toArray(new Integer[10]);
All we're doing here is creating a list, filling it with the integers 0-9, shuffling it, and writing the contents to an array.
If you want a more 'manual' approach, I'd suggest something like this:
List<Integer> l = new ArrayList<Integer>();
for (int i = 0; i < 10; i++)
l.add(i); // add 0-9
int[] ints = new int[10];
for (int i = 0 ; i < 10; i++)
ints[i] = l.remove((int)(Math.random() * l.size()));
System.out.println(Arrays.toString(ints));
[7, 2, 3, 4, 9, 6, 0, 1, 8, 5]
I'm assuming that you're allowed to use lists, since the code you posted includes a call to Arrays.asList.
It sounds like you're trying to generate a permutation of the numbers from 0 to 8 (9?). The easiest way to do this is to fill an array list with the numbers in sequence, and then use Collections.shuffle().

Trying to use a Hashmap<Integer, Integer>

how would I increment the key [i] by 1 in this situation every time I run through this for loop with the way I currently have it set up all the elements only get mapped to 1. I am trying to find out how many times each number occurs. I have tried +1 in the empty spot after list.get(i) but again only maps each element to 1. thank you.
List<Integer> list = new ArrayList<Integer>();
HashMap<Integer,Integer> Mode = new HashMap<Integer, Integer>();
for (int i = 0; i < arr.length; i++) {
for (int j = 0; j < arr[i].length; j++) {
list.add(arr[i][j]);
}
}
System.out.println(list);
int count = 1;
for(int i = 0; i < list.size(); i ++) {
Mode.put(list.get(i), );
You need to specify a Key here.
for(int i = 0; i < list.size(); i++) {
int value=list.get(i);
if(!Mode.containsKey(value))
Mode.put(value,1);
else
Mode.put(value,Mode.get(value)+1);
}
According to your comment,
for(int i = 0; i < list.size(); i ++) {
if(Mode.containsKey(list.get(i)) ){
Integer count = Mode.get(list.get(i));
Mode.put(list.get(i), ++count);}
else
Mode.put(list.get(i), 1);
If you have the option, you may find it easier to use something like Multiset from Guava.
Multiset<Integer> seen = HashMultiset.create();
for (int[] row : arr) {
for (int elem : row) {
seen.add(elem); // none of that nasty dealing with the Map
}
}
// you can look up the count of an element with seen.count(elem)
E mostCommon = null;
int highestCount = 0;
for (Multiset.Entry<Integer> entry : seen.entrySet()) {
if (entry.getCount() > highestCount) {
mostCommon = entry.getElement();
highestCount = entry.getCount();
}
}
return mostCommon; // this is the most common element

Categories