I created a method that fills an array with prime numbers. However, I am struggling to understand how can I return it after it has been filled to the main method to print it? Returning like this gives me an error that it cannot find such a symbol.
public static int[] fillArray(int a) {
int[] arr = new int[a];
int m = 0;
for (int i = 1; m < arr.length; i++) {
if (isPrime(i)) {
arr[m] = i;
m++;
}
}
return arr;
}
public static void main(String[] args) {
int a = Integer.parseInt(args[0]);
System.out.println(arr);
}
I would suggest, you can do something like below,
public static int[] fillArray(int a){
int[] arr = new int[a];
int m = 0;
for (int i = 1; m < arr.length; i++){
if (isPrime(i)){
arr[m] = i;
m++;
}
}
return arr;
}
public static void main(String[] args) {
int a = Integer.parseInt("5"); //Pass a hard coded value or Read it from Scanner class and pass the same as argument
int[] arr = fillArray(a);
System.out.println(arr); //This line not actually prints the values of array instead it prints the Object representation of the array
// Below small piece of code will print the values of the array
for(int val:arr){
System.out.println(val);
}
}
public static int[] fillArray(int a){
int[] arr = new int[a];
int m = 0;
for (int i = 1; m < arr.length; i++){
if (isPrime(i)){
arr[m] = i;
m++;
}
}
return arr;
}
public static void main(String[] args) {
int a = Integer.parseInt(args[0]);
int[] arr = fillArray(a); // This line was missing
System.out.println(Arrays.toString(arr));
}
Learn more about calling methods here: https://docs.oracle.com/javase/tutorial/java/javaOO/methods.html
Related
I have the following code that prints all k-subsequent of array of size n
import java.util.*;
public class Main {
public static void main(String[] args){
int[] arr = {1,2,3,4,5,6};
int k = 3;
int start= 0;
List<int[]> subs = subseq(arr, k, 0, new int[k]);
for(int[] s : subs)
System.out.println(Arrays.toString(s));
}
static List<int[]> subseq(int[] arr, int len, int start, int[] result){
List<int[]> rez = new ArrayList<>();
if (len == 0){
/* PRINT HERE WORKS FINE IT PRINT EACH SUBSEQUENT CORRECTLY*/
//System.out.println(Arrays.toString(result));
rez.add(result);
return rez;
}
for (int i = start; i <= arr.length-len; i++){
result[result.length - len] = arr[i];
subseq(arr, len-1, i+1, result);
}
return rez;
}
}
My issue is with rez List that is returned in recursive function, It always empty, can any one help fixing it ? I tried many solutions none worked
Basically, you were creating new arraylist to store all the sequences .You need to create a single result arraylist which will be storing all the arrays. While adding to res , i have created new array so that it does not replace the previous arrays that are added. Below is the working solution
import java.util.*;
public class Main {
public static void main(String[] args){
int[] arr = {1,2,3,4,5,6};
int k = 3;
int start= 0;
Main obj = new Main();
List<int[]> rez = new ArrayList<>();
obj.subseq(arr, k, start, new int[k], rez);
for(int[] s : rez)
System.out.println(Arrays.toString(s));
}
public void subseq(int[] arr, int len, int start,
int[] result, List<int[]>
res){
if (len == 0){
/* PRINT HERE WORKS FINE IT PRINT EACH SUBSEQUENT CORRECTLY*/
// System.out.println(Arrays.toString(result));
int[] a = new int[result.length];
for(int i = 0; i < result.length; i++) {
a[i] = result[i];
}
res.add(a);
return;
}
for (int i = start; i <=arr.length-len; i++){
result[result.length - len] = arr[i];
subseq(arr, len-1, i+1, result,res);
}
}
}
Hello I am having difficulty implementing a counting sort method in java. I believe the problem comes from the last two loops I have in the method. I am getting an ArrayIndexOutOfBounds exception : 8. I believe this comes from my second to last for loop when at index 5 the value is 8 but I am not sure how to resolve this. Any help is appreciated. Thank you!
In my code k is the highest value in the input array.
Code:
public static void main(String[] args) {
int [] arrayOne = {0,1,1,3,4,5,3,0};
int [] output = Arrays.copyOf(arrayOne, arrayOne.length);
System.out.println(Arrays.toString(arrayOne));
countingSort(arrayOne, output, 5);
System.out.println(Arrays.toString(output));
}
public static void countingSort(int[] input, int[] output , int k){
int [] temp = Arrays.copyOf(input, k+1);
for (int i = 0; i <= k; i++){
temp[i] = 0;
}
for (int j = 0; j <= input.length - 1; j++){
temp[input[j]] = temp[input[j]] + 1;
}
for (int i = 1; i <= k; i++){
temp[i] = temp[i] + temp[i-1];
}
for (int j = input.length; j >= 1; j--){
output[temp[input[j]]] = input[j];
temp[input[j]] = temp[input[j]] - 1;
}
}
The problem is in the first loop because the array temp lenght is 6 and you are doing 7 interations in there.
So at the end of the for it is trying to do temp[6]=0 and the last position of your array is temp[5].
To fix this change your first loop to:
for (int i = 0; i < k; i++){
In the last loop you will get the same exception cause input[8] doesn't exist.
import java.util.Arrays;
public class CountingSort {
public static void main(String[] args) {
int[] input = {0,1,1,3,4,5,3,0};
int[] output = new int[input.length];
int k = 5; // k is the largest number in the input array
System.out.println("before sorting:");
System.out.println(Arrays.toString(input));
output = countingSort(input, output, k);
System.out.println("after sorting:");
System.out.println(Arrays.toString(output));
}
public static int[] countingSort(int[] input, int[] output, int k) {
int counter[] = new int[k + 1];
for (int i : input) { counter[i]++; }
int ndx = 0;
for (int i = 0; i < counter.length; i++) {
while (0 < counter[i]) {
output[ndx++] = i;
counter[i]--;
}
}
return output;
}
}
Above code is adapted from: http://www.java67.com/2017/06/counting-sort-in-java-example.html
this may help but try using the Arraya.sort() method.
e.g:
//A Java program to sort an array of integers in ascending order.
// A sample Java program to sort an array of integers
// using Arrays.sort(). It by default sorts in
// ascending order
import java.util.Arrays;
public class SortExample
{
public static void main(String[] args)
{
// Our arr contains 8 elements
int[] arr = {13, 7, 6, 45, 21, 9, 101, 102};
Arrays.sort(arr);
System.out.printf("Modified arr[] : %s",
Arrays.toString(arr));
}
}
example is a snippet from https://www.geeksforgeeks.org/arrays-sort-in-java-with-examples/
As per algorithm following implementation, I have prepared for the count sort technique
public static int[] countSort(int elements[]) {
int[] sorted = new int[elements.length+1];
int[] range = new int[getMax(elements)+1];
for(int i=0;i<range.length;i++) {
range[i] = getCount(i, elements);
try {
range[i] = range[i]+range[i-1];
}catch(ArrayIndexOutOfBoundsException ae) {
continue;
}
}
for(int i=0;i<elements.length;i++) {
sorted[range[elements[i]]] = elements[i];
range[elements[i]] = range[elements[i]]-1;
}
return sorted;
}
public static int getCount(int value,int[] elements) {
int count = 0;
for(int element:elements) {
if(element==value) count++;
}
return count;
}
public static int getMax(int elements[]) {
int max = elements[0];
for(int i=0;i<elements.length;i++) {
if(max<elements[i]) {
max = elements[i];
}
}
return max;
}
Please review and let me know if any feedback and it is more helpful.
Note :
Non-negative no won't support in the above implementation.
don't use 0th index of the sorted array.
Had no luck the first time I had posted my question so I thought I would try again. I am a new Java programmer working on a little segment of code currently. In short I have created an array and a variable, what I would like this program to do is take the array and variable, pass it down to a method, have the method look at the array and if any of the numbers in the array are the same as the variable "8", take them out of the array "create a new array" return this array back to main and print it out.
I would like the array {2,4,8,19,32,17,17,18,25,17,8,3,4,8} to display {2,4,19,32,17,17,18,25,17,3,4} after being passed back to main please explain to me what I am doing wrong keep in mind I am brand new to java.
public class Harrison7b
{
public static void main(String [] args)
{
int[] arrayA = {2,4,8,19,32,17,17,18,25,17,8,3,4,8};
int varB = 8;
// Call with the array and variable you need to find.
int[] result = newSmallerArray(arrayA, varB);
for(int x = 0; x < arrayA.length; x++)
{
System.out.print(arrayA[x] + " ");
}
}
public static int[] newSmallerArray( int[] arrayA, int varB)
{
int count = 0;
for(int x = 0; x < arrayA.length; x++)
{
if(arrayA[x] == varB)
{
count++;
}
}
int [] arrayX = new int[arrayA.length - count];
int index = 0;
for(int B = 0; B < arrayA.length; B++)
{
if(arrayA[B] != varB)
{
index++;
}
}
return arrayX;
}
}
Simple one liner should suffice:
public static int[] newSmallerArray( int[] arrayA, int varB)
{
return Arrays.stream(arrayA).filter(i -> i != varB).toArray();
}
you missed to initialize array arrayX, try following solution
public class Harrison7b
{
public static void main(String [] args)
{
int[] arrayA = {2,4,8,19,32,17,17,18,25,17,8,3,4,8};
int varB = 8;
// Call with the array and variable you need to find.
int[] result = newSmallerArray(arrayA, varB);
for(int x = 0; x < result.length; x++) {
System.out.print(result[x] + " ");
}
}
public static int[] newSmallerArray( int[] arrayA, int varB)
{
int count = 0;
for(int x = 0; x < arrayA.length; x++)
{
if(arrayA[x] == varB)
{
count++;
}
}
int [] arrayX = new int[arrayA.length - count];
int index = 0;
for(int B = 0; B < arrayA.length; B++)
{
if(arrayA[B] != varB)
{
arrayX[index]= arrayA[B];
index++;
}
}
return arrayX;
}
}
public class lab {
public static void main (String args[]){
double[][] g = {RandomArray(3)};
printArray(g);
}
private static void printArray(double[][] g) {
System.out.println(Arrays.deepToString(g));
}
public static double[][] RandomArray(int n) {
double[] [] RandomArray = new double[n] [n];
Random randomNumberCreator = new Random();
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
RandomArray[i][j] = randomNumberCreator.nextDouble() * 100;
}
}
return RandomArray;
}
}
I am not sure what is wrong with my RandomArray method, i want it to work for 2-dimensional arrays but i have clearly made a mistake as the line below is receiving an error and I am unsure as to why this is happening. If you could explain to me the error that I have made i would be grateful.
double[][] g = {RandomArray(3)};
remove the curly brace around the function Call of "RandomArray"
public static void main (String args[]){
double[][] g = RandomArray(3);
printArray(g);
}
private static void printArray(double[][] g) {
System.out.println(Arrays.deepToString(g));
}
public static double[][] RandomArray(int n) {
double[] [] RandomArray = new double[n] [n];
Random randomNumberCreator = new Random();
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
RandomArray[i][j] = randomNumberCreator.nextDouble() * 100;
}
}
return RandomArray;
}
You are initializing the array incorrectly....
you dont need the { } when calling the method RandomArray
just doing double[][] g = RandomArray(3); will do the job
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)
}