This question already has answers here:
What's the simplest way to print a Java array?
(37 answers)
Closed 3 years ago.
Trying to save odd numbers between 2 numbers in an array
public class OddNumber {
static int[] oddNumbers(int l, int r) {
if (r <= l)
return null;
int size = ((r - l) / 2) + 1;
int arr[] = new int[size];
int p = 0;
for (int i = l; i <= r; i++) {
if (i % 2 != 0) {
arr[p] = i;
p++;
}
}
return arr;
}
public static void main(String[] args) {
System.out.println("Odd numbers between 2 & 9 are: " + oddNumbers(2, 9));
}
}
It is always giving same junk value "Odd numbers between 2 & 9 are: [I#15db9742". I dont know what is the problem
public class Solution {
static int[] oddNumbers(int l, int r) {
List<Integer> list = new ArrayList<>();
for (int i = l; i <= r; i++) {
if (i % 2 == 0) {
list.add(i);
}
}
int arr[] = new int[list.size()];
for(int i = 0 ; i < list.size(); i++) {
arr[i]=list.get(i);
}
return arr;
}
public static void main(String[] args) {
int arr[] = oddNumbers(2, 9);
for(int i : arr) {
System.out.print(i + " ");
}
}
}
Related
This is an exercise.
A perfect number is a number whose sum of divisors without itself is equal to that number
6 is a perfect number because its divisors are: 1,2,3,6 and 1 + 2 + 3 = 6
28 is a perfect number because its divisors are: 1,2,4,7,28 and 1 + 2 + 4 + 7 = 28
Task: write the body of findNPerfectNumbers, which will find n prime perfect numbers and return them as a list
I must use this program:
import java.util.ArrayList;
public class Exercise {
public static ArrayList<Integer> findNPerfectNumbers(int n)
{
return new ArrayList<>();
}
public static void main(String[] args)
{
System.out.println(findNPerfectNumbers(4));
}
}
I create this code to resolve this problem, but I have a problem to return an ArrayList. I don't know how. It should look like this example: 6 = 1,2,3,6 ///// 28 = 1, 2, 4, 7
My idea:
import java.util.ArrayList;
public class Main
{
public static ArrayList<Integer> findNPerfectNumbers(int n)
{
int sum = 0;
ArrayList<Integer> perfectList = new ArrayList<>();
ArrayList<Integer> factorList = new ArrayList<>();
for (int i = 6; i < n; i++)
{
factorList.clear();
for (int j = 1; j <= i / 2; j++)
{
if (i % j == 0)
{
factorList.add(j);
}
}
sum = 0;
for (int h = 0; h < factorList.size(); h++)
{
sum = sum + factorList.get(h);
}
if (sum == i)
{
perfectList.add(i);
}
}
return perfectList;
}
public static void main(String[] args)
{
System.out.println(findNPerfectNumbers(28));
}
}
Anyone have an idea?
The question is as simple as to have the findNPerfectNumbers function return the first N perfect numbers.
The main part for the exercise is probably to do this as efficiently as possible. For example limiting divider check by half like you do in for (int j = 1; j <= i / 2; j++) is one of many options.
The reason your function doesn't return anything though is because your outer for loop is incorrect with the given input of 4 what you'r doing is for (int i = 6; i < 4; i++) which doesn't do any loops because 4 is smaller than 6.
what you probably intended to do issomething like for (int i = 6; perfectList.size() < n; i++) which would loop aslong as you have fewer than N perfect numbers.
example working code:
import java.util.ArrayList;
public class Exercise {
public static ArrayList<Integer> findNPerfectNumbers(int n) {
int sum = 0;
ArrayList<Integer> perfectList = new ArrayList<>();
for (int i = 6; perfectList.size() < n; i++) {
ArrayList<Integer> factorList = new ArrayList<>();
for (int j = 1; j <= i / 2; j++) {
if (i % j == 0) {
factorList.add(j);
}
}
sum = 0;
for (Integer factor : factorList) {
sum += factor;
}
if (sum == i) {
System.out.println("Found perfect number " + i + " with factors " + factorList);
perfectList.add(i);
}
}
return perfectList;
}
public static void main(String[] args) {
System.out.println(findNPerfectNumbers(4));
}
}
If number is less than 10^1500 you can use Euclid's method
public static List<Long> findPerfect(int n){
List<Long> perfectList=new ArrayList<>();
int x=0;
long sum=0;
long last;
while(perfectList.size()!=n){
last= (long) Math.pow(2,x);
sum+=last;
if(isPrime(sum))
perfectList.add(sum*last);
x++;
}
return perfectList;
}
public static boolean isPrime(long x){
if(x==1)
return false;
for (int i = 2; i <= Math.sqrt(x); i++) {
if(x%i==0)
return false;
}
return true;
}
having issues with arrays sum and return. Algorithm is also having issues with a single value array. Idea is to sum up numbers and form a new array until there's only one value left. For example Array [1,2,3,2] turns into [3,5,5], [8,10] and finally [18]. What is the best way to sum up array values and return it?
public class Arraytest {
int count(int[] t) {
if (t.length > 1) {
int[] tt = new int[t.length - 1];
for (int i = 0; i < t.length - 1; i++) {
tt[i] += t[i] + t[i + 1];
System.out.println(tt[i]);
}
count(tt);
}
return 0;
}
}
public class Main {
public static void main(String[] args) {
Arraytest at = new Arraytest();
System.out.println(t.count(new int[] {1,2,3,4,5})); // 48
System.out.println(t.count(new int[] {2})); // 2
System.out.println(t.count(new int[] {7,1,1,3,8,2,9,5,4,2})); // 2538
}}
static int count(int[] t) {
if(t.length == 1)
return t[0];
else if (t.length > 1) {
int[] tt = new int[t.length - 1];
for (int i = 0; i < t.length - 1; i++)
tt[i] += t[i] + t[i + 1];
return count(tt);
}
return 0;
}
At the end you always returned zero instead of returning the last int in the array
Working Code:
public class Main {
public static void main(String[] args) {
Main t = new Main();
System.out.println(t.count(new int[] {1,2,3,4,5})[0]); // 48
System.out.println(t.count(new int[] {2})[0]); // 2
System.out.println(t.count(new int[] {7,1,1,3,8,2,9,5,4,2})[0]); // 323
}
static int[] count(int[] t) {
if(t.length == 1)
return t;
else if (t.length > 1) {
int[] tt = new int[t.length - 1];
for (int i = 0; i < t.length - 1; i++) {
tt[i] += t[i] + t[i + 1];
}
return count(tt);
}
return null;
}
}
public class OddsAndEvens {
// counts all the odd numbers in the array
private static int countOdds(int[] array) {
int count = 0;
for(int i = 0; i < array.length; i++) {
if(array[i] % 2 == 1 && array[i] % 2 != 0) {
count++;
}
}
return count;
}
// returns an array with all the odd numbers
public static int[] getAllOdds(int[] array) {
int[] yaArray = new int[countOdds(array)];
int j = 0;
for(int i = 0; i < array.length; i++) {
if(array[i] % 2 == 1 && array[i] % 2 != 0) {
yaArray[j] = array[i];
}
j++;
}
return yaArray;
}
}
///////////////////////////////////////////////////////////
runner code
public class OddsAndEvensRunner {
public static void main(String args[]) {
System.out.println("Odds - " + Arrays.toString(OddsAndEvens.getAllOdds(new int[]{2,4,6,8,10,12,14})));
System.out.println("Evens - " + Arrays.toString(OddsAndEvens.getAllEvens(new int[]{2,4,6,8,10,12,14})));
System.out.println("\nOdds - " + Arrays.toString(OddsAndEvens.getAllOdds(new int[]{1,2,3,4,5,6,7,8,9})));
System.out.println("Evens - " + Arrays.toString(OddsAndEvens.getAllEvens(new int[]{1,2,3,4,5,6,7,8,9})));
System.out.println("\nOdds - " + Arrays.toString(OddsAndEvens.getAllOdds(new int[]{2,10,20,21,23,24,40,55,60,61})));
System.out.println("Evens - " + Arrays.toString(OddsAndEvens.getAllEvens(new int[]{2,10,20,21,23,24,40,55,60,61})));
}
}
Ignore code relating to evens. When run the odd array only lists out one odd number instead of the others inside of the first array along with a couple of zeros. I tried a lot of things but simply won't count all of the odd numbers.
Take a look at this part:
public static int[] getAllOdds(int[] array) // when
{
int[] yaArray = new int[countOdds(array)];
int j = 0;
for(int i = 0; i<array.length;i++)
if(array[i]%2==1 && array[i]%2!=0)
yaArray[j]=array[i];
j++;
return yaArray;
}
The variable j is incremented only once, which is after the loop ends.
If you have multiple statements to be executed in looping or conditional branch, use brackets.
Also array[i]%2==1 means the same thing as array[i]%2!=0, so can eliminate one of them.
public static int[] getAllOdds(int[] array) // when
{
int[] yaArray = new int[countOdds(array)];
int j = 0;
for(int i = 0; i<array.length;i++)
{
if(array[i]%2==1)
{
yaArray[j]=array[i];
j++;
}
}
return yaArray;
}
Use List instead of Arrays. List is better to use.
Try like this,
public static void main(String[] args) {
System.out.println("Odds - " + Arrays.toString(getAllEvens(new int[] { 1, 2, 3, 4, 5, 6, 7, 8, 9 })));
System.out.println("Evens - " + Arrays.toString(getAllOdds(new int[] { 1, 2, 3, 4, 5, 6, 7, 8, 9 })));
}
public static Object[] getAllOdds(int[] array) {
List<Integer> list = new ArrayList<>();
for (int no : array) {
if (no % 2 != 0)
list.add(no);
}
return list.toArray();
}
public static Object[] getAllEvens(int[] array) {
List<Integer> list = new ArrayList<>();
for (int no : array) {
if (no % 2 == 0)
list.add(no);
}
return list.toArray();
}
You can also return list instead of list.toArray() for better list.
Okay, so i need to find all the negative numbers of array and return them.I found the negative number, but how do i return them all? P.S yes i am a beginner.
public static void main(String[] args) {
int [] array = {5,-1,6,3,-20,10,20,-5,2};
System.out.println(findNumber(array));
}
public static int findNumber(int[] sum) {
int num = 0;
for (int i = 0; i < sum.length ; i++) {
if(sum[i] < num) {
num = sum[i];
}
}
return num;
}
Java 8 based solution. You can use stream to filter out numbers greater than or equal to zero
public static int[] findNumber(int[] sum)
{
return Arrays.stream(sum).filter(i -> i < 0).toArray();
}
There are multiple ways of doing this, if you just want to output all of the negative numbers easily you could do this:
public static void main(String[] args) {
int [] array = {5,-1,6,3,-20,10,20,-5,2};
ArrayList<Integer> negativeNumbers = findNumber(sum);
for(Integer negNum : negativeNumbers) {
System.out.println(negNum);
}
}
public static ArrayList<Integer> findNumber(int[] sum) {
ArrayList<Integer> negativeNumbers = new ArrayList<>();
for (int i = 0; i < sum.length ; i++) {
if(sum[i] < 0) {
negativeNumber.add(sum[i]);
}
}
return negativeNumbers;
}
As you told you are beginner, i'm giving code in using arrays only.
Whenever you come across a negative number, just add it to the array and increment it's index number and after checking all the numbers, return the array and print it.
public static void main(String[] args)
{
int [] array = {5,-1,6,3,-20,10,20,-5,2};
int[] neg = findNumber(array);
for(int i = 0 ; i<neg.length; i++)
{
System.out.println(neg[i]);
}
}
public static int[] findNumber(int[] a)
{
int j=0;
int[] n = new int[a.length];
for(int i = 0; i<a.length ; i++)
{
if(a[i] <0)
{
n[j] = a[i];
j++;
}
}
int[] neg = new int[j];
for( int k = 0 ; k < j ; k++)
{
neg[k] = n[k];
}
return neg;
}
I hope it helps.
You can modify your method to iterate through the array of numbers, and add every negative number you encounter, to a List.
public static List<Integers> findNegativeNumbers(int[] num) {
List<Integers> negativeNumbers = new ArrayList<>();
for (int i = 0; i < num.length; i++) {
if(num[i] < 0) {
negativeNumbers.add(num[i]);
}
}
return negativeNumbers;
}
You could then print out the list of negative numbers from this method itself, or return the list with return to be printed in main.
You code is returning the sum of elements, but I understood that you wanted every negative number.
So, I assumed you want something like this:
public static void main(String[] args) {
int [] array = {5,-1,6,3,-20,10,20,-5,2};
Integer [] result = findNumbers( array );
for( int i : result )
{
System.out.println( i );
}
}
public static Integer[] findNumbers(int[] v) {
List<Integer> list = new ArrayList<>();
for (int i = 0; i < v.length ; i++) {
if(v[i] < 0) {
list.add(v[i]);
}
}
return list.toArray( new Integer[0] );
}
Is it?
Best regards.
public static int[] findNum(int[] array)
{
int negativeIntCount = 0;
int[] negativeNumbers = new int[array.length];
for(int i = 0; i < array.length; i++)
{
if(array[i] < 0)
{
negativeIntCount++;
negativeNumbers[i] = array[i];
}
}
System.out.println("Total negative numbers in given arrays is " + negativeIntCount);
return negativeNumbers;
}
To display as an array in output :
System.out.println(Arrays.toString(findNum(array)));
To display output as space gaped integers :
for(int x : findNum(array))
{
System.out.print(" " + x)
}
This question already has answers here:
Getting permutations of an int[] removing duplicates sets
(5 answers)
Closed 7 years ago.
I've just written a code for printing all the possible permutations from 1 to n in an int array in Java, but I think it is more complex than it needs to be. I am using Hashset to avoid repetitions. If someone finds something than can be simplified, please write.
import java.util.*;
public class ProblemFour {
private static int n;
private static void printResult(int[] result) {
Set<Integer> set = new HashSet<>();
Integer[] nums = new Integer[result.length];
for (int i = 1; i <= n; i++) {
nums[i - 1] = result[i - 1];
}
for (Integer num : nums) {
set.add(num);
}
if(set.size() == n) {
String s = "[ ";
for (Integer num : nums) {
s += num + " ";
}
System.out.println(s + "] ");
}
}
private static void permute(int[] result, int index) {
if (index == result.length) {
printResult(result);
return;
}
for (int i = 1; i <= n; i++) {
result[index] = i;
permute(result, index+1);
}
}
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("From 1 to: ");
n = input.nextInt();
int[] result = new int[n];
permute(result, 0);
}
}
I made this permutations code way back it uses lists as a data structure in it.
public List<List<Integer>> permute(int[] numbers) {
// we use a list of lists rather than a list of arrays
// because lists support adding in the middle
// and track current length
List<List<Integer>> permutations = new ArrayList<List<Integer>>();
// Add an empty list so that the middle for loop runs
permutations.add(new ArrayList<Integer>());
for ( int i = 0; i < numbers.length; i++ ) {
// create a temporary container to hold the new permutations
// while we iterate over the old ones
List<List<Integer>> current = new ArrayList<List<Integer>>();
for ( List<Integer> permutation : permutations ) {
for ( int j = 0, n = permutation.size() + 1; j < n; j++ ) {
List<Integer> temp = new ArrayList<Integer>(permutation);
temp.add(j, numbers[i]);
current.add(temp);
}
}
permutations = new ArrayList<List<Integer>>(current);
}
return permutations;
}