Aleksander L.
asked 02/04/21Need help with some questions
What's a method that will take an int array list and will take every even number in the list and insert the same number to the right of the initial number. e.g.: [1,2,3,4] would become [1,2,2,3,4,4]
What's a method that will take an array list and move all the odd numbers to be before the even numbers. e.g.: [1,2,3,4] would become [1,3,2,4]
What's a method that will take an array list and square all the numbers in the list. e.g.:[1,2,3,4] would become [1,4,9,16]
3 Answers By Expert Tutors
Dayaan M. answered 7d
Computer Science Graduate with Computer Engineering Coursework
All three of these are doable in a few lines each if you use ArrayList methods. The other answers here are written in C with raw arrays and malloc, which will not compile as Java and does not use an array list, so here they are the way your question is actually asking for.
1. Duplicate every even number.
public static void duplicateEvens(ArrayList<Integer> list) {
for (int i = 0; i < list.size(); i++) {
if (list.get(i) % 2 == 0) {
list.add(i + 1, list.get(i));
i++;
}
}
}
The line that matters most here is the i++ inside the if. The two argument add inserts at an index and pushes everything else right, so the copy you just made lands at position i + 1, which is where the loop is about to look. Without that extra i++ the loop sees the copy, decides it is even, duplicates it again, and you get an infinite loop that runs until memory runs out. This is the single most common way this exercise goes wrong.
Also note list.size() is being called fresh every pass, so the loop correctly accounts for the list growing.
2. Move the odd numbers before the even numbers.
public static void oddsFirst(ArrayList<Integer> list) {
ArrayList<Integer> odds = new ArrayList<>();
ArrayList<Integer> evens = new ArrayList<>();
for (int v : list) {
if (v % 2 == 0) { evens.add(v); } else { odds.add(v); }
}
list.clear();
list.addAll(odds);
list.addAll(evens);
}
You could try to swap elements around in place instead, but sorting two buckets and gluing them back together is easier to get right and it keeps the original relative order, so [1,2,3,4] gives [1,3,2,4] exactly as your example shows rather than some other valid but unexpected arrangement.
3. Square every number.
public static void squareAll(ArrayList<Integer> list) {
for (int i = 0; i < list.size(); i++) {
list.set(i, list.get(i) * list.get(i));
}
}
Use set and not add here, since set replaces the value at that index while add would insert a new one. And this needs the indexed loop rather than a for each loop, because a for each variable is just a copy of the value and assigning to it changes nothing in the list.
I compiled and ran all three before posting, and on [1,2,3,4] they give [1, 2, 2, 3, 4, 4], [1, 3, 2, 4] and [1, 4, 9, 16], which matches your examples. They also behave on an empty list and on negative numbers.
One last gotcha worth knowing since these are Integer and not int: if you ever need to delete by value, list.remove(someInt) removes by index while list.remove(Integer.valueOf(someInt)) removes by value. None of the three methods above need it, but it catches almost everyone eventually.
Inactive Tutor answered 02/04/21
using namespace std;
#include <iostream>
#include <stdlib.h>
#include <string.h>
int CompareInt(const void * rec1, const void * rec2)
{
int * intPtr1 = (int*)rec1;
int * intPtr2 = (int*)rec2;
int iNum1=*intPtr1;
int iNum2=*intPtr2;
return(iNum1-iNum2);
}
int duplicateEvens(int * a, int * aDup, int N)
{
int iIndexPos=0;
for (int iLoop=0; iLoop<N; iLoop++)
{
aDup[iIndexPos++]=a[iLoop];
if ((a[iLoop])%2 == 0)
{
aDup[iIndexPos++]=a[iLoop];
}
}
return(iIndexPos);
}
int oddEvenSort(int * a, int * aResult, int N )
{
int * evens = (int*)malloc(N*sizeof(int));
int * odds = (int*)malloc(N*sizeof(int));
int oddIndex=0;
int evenIndex=0;
for (int iLoop=0; iLoop<N; iLoop++)
{
if (a[iLoop]%2==0)
{
evens[evenIndex++]=a[iLoop];
}
else
{
odds[oddIndex++]=a[iLoop];
}
}
qsort(evens,evenIndex,sizeof(int),CompareInt);
qsort(odds,oddIndex,sizeof(int),CompareInt);
memcpy(aResult,odds,oddIndex*sizeof(int));
memcpy(&aResult[oddIndex],evens,evenIndex*sizeof(int));
free(odds);
free(evens);
}
Squares(int * a, int * aSqr, int N)
{
for (int iLoop=0; iLoop<N; iLoop++)
{
aSqr[iLoop] = a[iLoop]*a[iLoop];
}
}
int main()
{
int a[]={1,2,3,4};
int dupEvens[8];
int OddEvenSort[4];
int aSquares[4];
int iReturn = duplicateEvens(a,dupEvens,4);
cout << "duplicate evens " << endl;
for (int iLoop=0; iLoop<iReturn; iLoop++)
{
cout << dupEvens[iLoop] << endl;
}
cout << "****************************************" << endl;
cout << "odd even sort " << endl;
oddEvenSort(a,OddEvenSort,4);
for (int iLoop=0; iLoop<4; iLoop++)
{
cout << OddEvenSort[iLoop] << endl;
}
cout << "*******************************************" << endl;
cout << " Squares " << endl;
Squares(a,aSquares,4);
for (int iLoop=0; iLoop<4; iLoop++)
{
cout << aSquares[iLoop] << endl;
}
}
/*************************************************************************************************/
#*********** PYTHON ************************************
def dupEven( a):
N = len(a)
results=[]
for i in range(N):
results.append(a[i])
if (a[i]%2==0):
results.append(a[i])
return(results)
#********************************************************************************
def dupOdd( a):
N = len(a)
results=[]
for i in range(N):
results.append(a[i])
if (a[i]%2==1):
results.append(a[i])
return(results)
#***************************************************
def evenOddSort(a):
N = len(a)
odds=[]
evens=[]
for i in range(N):
if a[i]%2==0:
evens.append(a[i])
else:
odds.append(a[i])
odds.sort()
evens.sort()
results=[]
nOdds = len(odds)
for i in range(nOdds):
results.append(odds[i])
nEvens =len(evens)
for i in range(nEvens):
results.append(evens[i])
return results
#**************************************************
def Square(A):
results=[]
N=len(A)
for i in range(N):
results.append(A[i]*A[i])
return results
#******************************************************
A=[1,2,3,4]
results = dupEven(A)
print(results)
results = dupOdd(A)
print(results)
results = evenOddSort(A)
print(results)
results = Square(A)
print(results)
Inactive Tutor answered 02/04/21
Question: What's a method that will take an int array list and will take every even number in the list and insert the same number to the right of the initial number. e.g.: [1,2,3,4] would become [1,2,2,3,4,4]
Answer: The method needs to loop through the array, checking each value and inserting a duplicate if the value is even. The trick is that the loop index needs to increase by 2 when the value is even, so as to skip to the next value in the array. That means that the loop index incrementing should be done in the body of the loop, not the for loop itself (if you're using a for-loop). Secondly, the length of the list needs to be calculated each time by the for-loop, which should happen if you're using the array's size or length method.
Question: What's a method that will take an array list and move all the odd numbers to be before the even numbers. e.g.: [1,2,3,4] would become [1,3,2,4]
Answer: The method needs to loop through the array, moving the odd numbers to the beginning of the list based on an insert index that increases each time another odd number is found. ["Move" means remove and insert.] Initially the index should be initialized to 0. Don't worry about the case where an odd number is the first element in the list - the algorithm will still work.
Question: What's a method that will take an array list and square all the numbers in the list. e.g.:[1,2,3,4] would become [1,4,9,16]
Answer: The method needs to loop through the array, replacing each number by its square.
Still looking for help? Get the right answer, fast.
Get a free answer to a quick problem.
Most questions answered within 4 hours.
OR
Choose an expert and meet online. No packages or subscriptions, pay only for the time you need.
Inactive Tutor
You did NOT specify the programming language02/04/21