The method does not print the last odd value in the array. I tried array.size() - 1, but to no avail. What am I doing wrong?
import java.util.ArrayList;
public class Odds
{
public static void main(String[] args)
{
ArrayList<Integer> odds = new ArrayList<Integer>();
for(int index = 1; index <101; index++)
{
odds.add(index);
removeEvens(odds);
}
//call removeEvens on the array above!
}
public static void removeEvens(ArrayList<Integer> array)
{
for(int i = 0; i < array.size(); i++)
{
if (array.get(i)%2 == 0)
{
array.remove(i);
i--;
System.out.println(array.get(i));
}
if(i==array.size())
{
System.out.println(array.size() - 1);
}
}
}
}
You should address the following things in your code:
Do not call removeEvens(odds) inside the loop. Call it after the list is initialized.
Do not decrement the value of i explicitly.
You should do it as follows:
import java.util.ArrayList;
public class Odds {
public static void main(String[] args) {
ArrayList<Integer> odds = new ArrayList<Integer>();
for (int index = 1; index < 101; index++) {
odds.add(index);
}
removeEvens(odds);
System.out.println(odds);
}
public static void removeEvens(ArrayList<Integer> array) {
for (int i = 0; i < array.size(); i++) {
if (array.get(i) % 2 == 0) {
array.remove(i);
}
}
}
}
Output:
[1, 3, 5, 7, 9, 11, 13, 15, 17, 19, 21, 23, 25, 27, 29, 31, 33, 35, 37, 39, 41, 43, 45, 47, 49, 51, 53, 55, 57, 59, 61, 63, 65, 67, 69, 71, 73, 75, 77, 79, 81, 83, 85, 87, 89, 91, 93, 95, 97, 99]
I tend to prefer using explicit iterators when doing this kind of modification.
List<Integer> odds = new ArrayList<>(List.of(1,2,3,4,5,6,7));
Iterator<Integer> it = odds.iterator();
while(it.hasNext()) {
if (it.next() % 2 == 0) {
it.remove();
}
}
And then there is the Streams version which passes the odds on down the stream for collection.
odds = odds.stream().filter(a->a%2 == 1).collect(Collectors.toList());
Both results are
[1, 3, 5, 7]
Related
This question already has answers here:
How to sum a row in a matrix
(6 answers)
Closed 2 years ago.
I have an array as listen in the code below and I must use the method sumRow but im not sure how to do it, most tutorials online are of no help to me. I know it seems easy but if someone could help or explain it to me that would be awesome
code:
public class Sum
{
public static void main(String[] args)
{
int[][] array = {{32, 4, 14, 65, 23, 6},
{4, 2, 53, 31, 765, 34},
{64235, 23, 522, 124, 42, 64}};
}
public static int sumRow(int[][] array, int row)
{
//This is where the sumRow method is supposed to be made.
}
}
Use Arrays.stream(arr).sum():
public static int sumRow(int[][] array, int row) {
if (row < 0 || row >= array.length) return -1; // row is not valid
return Arrays.stream(array[row]).sum();
}
public class Sum {
public static void main(String[] args) {
int[][] array = {{32, 4, 14, 65, 23, 6},
{4, 2, 53, 31, 765, 34},
{64235, 23, 522, 124, 42, 64}};
}
public static int sumRow(int[][] array, int row) {
int sum = 0;
for (int col = 0; col < array[row].length; col++) {
sum += array[row][col];
}
return sum;
}
}
Iterate the row of the array and add each element to sum where int sum has been initialized with 0.
Demo:
public class Main {
public static void main(String[] args) throws IllegalArgumentException {
int[][] array = { { 32, 4, 14, 65, 23, 6 },
{ 4, 2, 53, 31, 765, 34 },
{ 64235, 23, 522, 124, 42, 64 } };
// Test
System.out.println(sumRow(array, 0));
System.out.println(sumRow(array, 1));
System.out.println(sumRow(array, 2));
System.out.println(sumRow(array, 5));
System.out.println(sumRow(array, -1));
}
public static int sumRow(int[][] array, int row) throws IllegalArgumentException {
int sum = 0;
if (row >= 0 && row < array.length) {
for (int i = 0; i < array[row].length; i++) {
sum += array[row][i];
}
} else {
throw new IllegalArgumentException("The row number should be >=0 and <" + array.length);
}
return sum;
}
}
Output:
144
889
65010
Exception in thread "main" java.lang.IllegalArgumentException: The row number should be >=0 and <3
at Main.sumRow(Main.java:22)
at Main.main(Main.java:11)
Another demo (with exception handled):
public class Main {
public static void main(String[] args) throws IllegalArgumentException {
int[][] array = { { 32, 4, 14, 65, 23, 6 },
{ 4, 2, 53, 31, 765, 34 },
{ 64235, 23, 522, 124, 42, 64 } };
// Test
for (int i = -1; i < 4; i++) {
try {
System.out.println("Sum of row, " + i + ": " + sumRow(array, i));
} catch (IllegalArgumentException e) {
System.out.println(e.getMessage());
}
}
}
public static int sumRow(int[][] array, int row) throws IllegalArgumentException {
int sum = 0;
if (row >= 0 && row < array.length) {
for (int i = 0; i < array[row].length; i++) {
sum += array[row][i];
}
} else {
throw new IllegalArgumentException("The row number should be >=0 and <" + array.length);
}
return sum;
}
}
Output:
The row number should be >=0 and <3
Sum of row, 0: 144
Sum of row, 1: 889
Sum of row, 2: 65010
The row number should be >=0 and <3
I need help with figuring out how to combine two char arrays and then have the elements alternate in a new array. The given arrays can be different lengths, for example: char1=[B,D] char2 = [c,R,5] the output should be char3= [B,c,D,r,5]
char[] ch3 = new char[ch1.length + ch2.length];
int count = 0;
int count2 = 0;
for(int i = 0; i < ch3.length; i++){
if(i < ch1.length) {
if(i%2 == 0 || count2 == ch2.length) {
ch3[i] = ch1[count];
count++;
}
}
if(i <ch2.length) {
if(i%2 != 0 || count == ch1.length) {
ch3[i] = ch2[count2];
count2++;
}
}
}
return ch3;
Similar solution to answer by oleg.cherednik, but without the need for slow % remainder operator.
public static int[] alternate(int[] a1, int[] a2) {
int[] a3 = new int[a1.length + a2.length];
for (int i1 = 0, i2 = 0, i3 = 0; i3 < a3.length; ) {
if (i1 < a1.length)
a3[i3++] = a1[i1++];
if (i2 < a2.length)
a3[i3++] = a2[i2++];
}
return a3;
}
Tests
System.out.println(Arrays.toString(alternate(
new int[] { 1, 2, 3 },
new int[] { 44, 55, 66, 77, 88 })));
System.out.println(Arrays.toString(alternate(
new int[] { 44, 55, 66, 77, 88 },
new int[] { 1, 2, 3 })));
Output
[1, 44, 2, 55, 3, 66, 77, 88]
[44, 1, 55, 2, 66, 3, 77, 88]
UPDATE
This algorithm can easily be enhanced to merge many arrays:
public static int[] alternate(int[]... arrays) {
int[] result = new int[Stream.of(arrays).mapToInt(a -> a.length).sum()];
int[] ai = new int[arrays.length];
for (int j = 0; j < result.length; )
for (int i = 0; i < arrays.length; i++)
if (ai[i] < arrays[i].length)
result[j++] = arrays[i][ai[i]++];
return result;
}
Test
System.out.println(Arrays.toString(alternate(
new int[] { 1, 2, 3 },
new int[] { 44, 55, 66, 77, 88 },
new int[] { 12, 34 },
new int[] { 5, 6, 7, 8 })));
Output
[1, 44, 12, 5, 2, 55, 34, 6, 3, 66, 7, 77, 8, 88]
UPDATE 2
It can also be done for collections:
#SafeVarargs
public static <T> List<T> alternate(Iterable<? extends T>... inputs) {
List<T> result = new ArrayList<>();
#SuppressWarnings("unchecked")
Iterator<? extends T>[] iter = new Iterator[inputs.length];
for (int i = 0; i < inputs.length; i++)
iter[i] = inputs[i].iterator();
for (int prevSize = -1; prevSize < result.size(); ) {
prevSize = result.size();
for (int i = 0; i < inputs.length; i++)
if (iter[i].hasNext())
result.add(iter[i].next());
}
return result;
}
public static <T> List<T> alternate(Collection<? extends Iterable<? extends T>> inputs) {
#SuppressWarnings("unchecked")
Iterable<? extends T>[] iterables = inputs.toArray(new Iterable[0]);
return alternate(iterables);
}
Tests
System.out.println(alternate(
Arrays.asList(1, 2, 3),
Arrays.asList(44, 55, 66, 77, 88),
Arrays.asList(12, 34),
Arrays.asList(5, 6, 7, 8)));
System.out.println(alternate(Arrays.asList(
Arrays.asList(1, 2, 3),
Arrays.asList(44, 55, 66, 77, 88),
Arrays.asList(12, 34),
Arrays.asList(5, 6, 7, 8))));
Output
[1, 44, 12, 5, 2, 55, 34, 6, 3, 66, 7, 77, 8, 88]
[1, 44, 12, 5, 2, 55, 34, 6, 3, 66, 7, 77, 8, 88]
public static void main(String... args) {
int[] one = { 1, 2, 3 };
int[] two = { 44, 55, 66, 77, 88 };
System.out.println(Arrays.toString(alternate(one, two)));
}
public static int[] alternate(int[] one, int[] two) {
// result array length is sum of lengths of given arrays.
int[] res = new int[one.length + two.length];
// i - result array iterator
// j - one array iterator
// k - two array iterarot
for (int i = 0, j = 0, k = 0; i < res.length; i++) {
// for even position we put next element from one array
if (i % 2 == 0)
// if one array has more elements - add it
// if no more elements in one array, add next element from two array
if (j < one.length)
res[i] = one[j++];
else
res[i] = two[k++];
// for odd position we put next element from two array
else
// if two array has more elements - add it
// if no more elements in two array, add next element from one array
if (k < two.length)
res[i] = two[k++];
else
res[i] = one[j++];
}
return res;
}
Output:
[1, 44, 2, 55, 3, 66, 77, 88]
I'm new to programming and Stack-overflow but I'm trying to create a list of prime factors from a number but it is returning more than one list and I don't know why. For example when I enter 10, it returns [2,5] and [2,5,5] instead of just [2,5]. Can someone explain what I'm doing wrong?
public class Solution {
ArrayList<Integer> primelist = new ArrayList<>();
ArrayList<Integer> findPrime(int num) {
for (int i = 2; i <= num; i++) {
if (num % i == 0) {
primelist.add(i);
num = num / i;
if (num == 1) { break;}
findPrime(num);
}
}
System.out.println(primelist);
return primelist;
}
public static void main(String[] args) {
Solution sol = new Solution();
sol.findPrime(30);//[2, 3, 5],[2, 3, 5, 5], [2, 3, 5, 5, 3, 5],[2, 3, 5, 5, 3, 5, 5]
sol.findPrime(10);//[2, 5],[2, 5, 5]
}
}
Im guessing you try to achieve the Sieve of Eratosthenes.
this works:
#Test
public void numbers() {
class Solution {
List<Integer> sieveOfEratosthenes(int n) {
boolean prime[] = new boolean[n + 1];
Arrays.fill(prime, true);
for (int p = 2; p * p <= n; p++) {
if (prime[p]) {
for (int i = p * 2; i <= n; i += p) {
prime[i] = false;
}
}
}
List<Integer> primeNumbers = new LinkedList<>();
for (int i = 2; i <= n; i++) {
if (prime[i]) {
primeNumbers.add(i);
}
}
return primeNumbers;
}
}
//test it..
Solution sol = new Solution();
System.out.println(sol.sieveOfEratosthenes(10));
System.out.println(sol.sieveOfEratosthenes(100));
}
... which yields correct results:
[2, 3, 5, 7]
[2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97]
i borrowed this code from this article, an detailed explanation of the steps of the algorithm can be found there.
The following is for one of my assignments in my java programming class. I have all the code written already I just can't figure how to make the output display what i need it to display.
For my assignment I have to write a program with a single-dimension array that holds 10 integer numbers between 1 and 100 and sort the array using a bubble sort.
An example of what the output needs to look like is this:
The unsorted list is: 54, 27, 13, 97, 5, 63, 78, 34, 47, and 81
The sorted list is: 5, 13, 27, 34, 47, 54, 63, 78, 81, and 97
My output is displaying this:
The unsorted list is: 54, 27, 13, 97, 5, 63, 78, 34, 47, 81,
The sorted list is: 5, 13, 27, 34, 47, 54, 63, 78, 81, 97,
I can't figure out how to write the "and" into the output.
public class Chpt7_Project {
/** The method for sorting the numbers */
public static void bubbleSort(int[] numbers)
{
int temp;
for (int i = numbers.length - 1; i > 0; i--)
{
for (int j = 0; j < i; j++)
{
if (numbers[j] > numbers[j + 1])
{
temp = numbers[j]; // swap number[i] with number[j]
numbers[j] = numbers[j + 1];
numbers[j + 1] = temp;
}
}
}
}
public static void main(String[] args) { // Test Method
System.out.print("The unsorted list is: ");
// Generate 10 random numbers between 1 and 100
int[] numbers = new int[10];
for (int i=0;i<numbers.length;i++) {
numbers[i] = (int) (Math.random() * 100);
System.out.print(numbers[i] + ", ");
}
System.out.println();
bubbleSort (numbers); // numbers are sorted from smallest to largest
System.out.print("The sorted list is: ");
for (int i=0;i<numbers.length;i++) {
System.out.print(numbers[i] + ", ");
}
}
}
Change this loop
for (int i=0;i<numbers.length;i++) {
System.out.print(numbers[i] + ", ");
}
to
for (int i=0;i<numbers.length;i++) {
if(i== numbers.length-1) {
System.out.println("and "+numbers[i]);
} else {
System.out.print(numbers[i] + ", ");
}
}
Output:
The unsorted list is: 67, 86, 78, 80, 56, 45, 24, 2, 67, and 98
The sorted list is: 2, 24, 45, 56, 67, 67, 78, 80, 86, and 98
Modified Code(Integrated what #abhinav mentioned):
public class Chpt7_Project {
/** The method for sorting the numbers */
public static void bubbleSort(int[] numbers) {
int temp;
for (int i = numbers.length - 1; i > 0; i--) {
for (int j = 0; j < i; j++) {
if (numbers[j] > numbers[j + 1]) {
temp = numbers[j]; // swap number[i] with number[j]
numbers[j] = numbers[j + 1];
numbers[j + 1] = temp;
}
}
}
}
public static void main(String[] args) { // Test Method
System.out.print("The unsorted list is: ");
// Generate 10 random numbers between 1 and 100
int[] numbers = new int[10];
for (int i=0;i<numbers.length;i++) {
numbers[i] = (int) (Math.random() * 100);
if(i== numbers.length-1) {
System.out.println("and "+numbers[i]);
} else {
System.out.print(numbers[i] + ", ");
}
}
System.out.println();
bubbleSort (numbers); // numbers are sorted from smallest to largest
System.out.print("The sorted list is: ");
for (int i=0;i<numbers.length;i++) {
if(i== numbers.length-1) {
System.out.println("and "+numbers[i]);
} else {
System.out.print(numbers[i] + ", ");
}
}
}
}
Is it possible to get the index of a 2D array?
Suppose I have the following array
int[][] arr = {{41, 44, 51, 71, 63, 1}, {7, 88, 31, 95, 9, 6}, {88, 99, 6, 5, 77, 4}};
And I want to get the index of 88, how to do it?
for (int i = 0 ; i < size; i++)
for(int j = 0 ; j < size ; j++)
{
if ( arr[i][j] == 88)
{
`save this 2 indexes`
break;
}
}
If they are not sorted, you will have to loop through all indexes [using double loop] and check if it is a match.
int[][] arr = {{41, 44, 51, 71, 63, 1}, {7, 88, 31, 95, 9, 6}, {88, 99, 6, 5, 77, 4}};
for (int i = 0; i < arr.length; i++) {
for (int j = 0; j < arr[i].length; j++) {
if (arr[i][j] == 88) {
System.out.println("i=" + i + " j=" + j);
}
}
}
will result in:
i=1 j=1
i=2 j=0
This is a primitive array, so it should be directly accessibly with the index:
int[] indexValue = arr[88];
EDIT:
Sorry, reading it again, if you mean the indices of the item 88 then there are multiple occurrences of 88 so you would need to iterate through each index and look for a match in each, and also have the size of the arrays stored somewhere. If it's possible and doesn't impact on performance, use an ArrayList or Vector and store Integers objects instead.
System.out.println(Arrays.toString(da(arr,88)));
}
static int[] da(int dt[][],int target){
for(int i=0;i<dt.length;i++){
for (int j = 0; j <dt[i].length ; j++) {
if(dt[i][j]==target){
return new int[]{i,j};
}
}
}
return new int[]{-1,-1};
}
}