I need to return value from method permutation
public void permute(int []a,int k ) {
if(k==a.length)
jTextArea1.append(Arrays.toString(a)+"\n");
else
for (int i = k; i< a.length; i++) {
int temp=a[k];
a[k]=a[i];
a[i]=temp;
permute(a,k+1);
temp=a[k];
a[k]=a[i];
a[i]=temp;
}
}
so what I need how to convert that to this
public int[] permute(int []a,int k ) {
.....
}
for expmle I have this code main
public static void main(String[] args) {
Permutation p=new Permutation();
int a[]={1,2,3};
//p.permute(a, 0);
System.out.println((p.permute(a, 0)));
}
works .
but I need to do thats
public int[] permute(int []a,int k ) {
return
}
and give the result all permutation of a
I found the solution and I share the solation
public ArrayList<ArrayList<Integer>> permute(int[] num) {
ArrayList<ArrayList<Integer>> result = new ArrayList<ArrayList<Integer>>();
//start from an empty list
result.add(new ArrayList<Integer>());
for (int i = 0; i < num.length; i++) {
ArrayList<ArrayList<Integer>> current = new ArrayList<ArrayList<Integer>>();
for (ArrayList<Integer> l : result) {
for (int j = 0; j < l.size()+1; j++) {
l.add(j, num[i]);
ArrayList<Integer> temp = new ArrayList<Integer>(l);
current.add(temp);
l.remove(j);
}
}
result = new ArrayList<ArrayList<Integer>>(current);
}
return result;
}
Related
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
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)
}
I have a 2D array , iam trying to calculate the minimum value for each column and put the result in the result array.
the code bellow is calculating the minimum value for each row , how can i get the min value for each column.
import java.util.*;
class Test20 {
public static void main ( String [] args) {
int[][] array = {{6,3,9},
{0,8,2},
{3,7,5}};
Test20 test = new Test20();
System.out.print(Arrays.toString(test.mincol(array)));
}
public static int[] mincol (int[][] n) {
int[] result = new int[n.length];
for (int i = 0; i < n.length; i++) {
int min = n[0][i];
for (int j = 0; j < n[0].length; j++) {
if (n[j][i] < min) {
min = n[j][i];
}
}
result[i] = min;
}
return result;
}
}
Just change the loop the following way:
min = 0;
for(int i=0;i<n.length;i++){
for(int j=0;j<n[0].length;j++){
if(n[j][i]<n[j][min]){
min=j;
}
result[i]=n[min][i];
}
Be aware that you instantiate your result array by the length of the first dimension in your array but later use the n[][] param for looping and access the length of the second dimension in your loop.
If your two dim array is for example 4x5, this will cause ArrayOutOfBoundsExceptions.
You only need to do the same thing but inverting the variables
for(int i=0;i<n.length;i++){
for(int j=0;j<n[0].length;j++){
if(n[j][i]<n[min][j]){
min=i;
}
result[j]=n[min][j];
}
}
If your code is correct just change:
if(n[i][j]<n[i][min]){
min=j;
}
with
if(n[i][j]<n[result[i]][j]){
result[i]=i;
}
finally
for(int i=0;i<n.length;i++) result[i]=n[result[i][j];
you don't need min. But change
int [] result = new int[n.length];
to
int [] result = new int[n[0].length];
How about you transpose your two dimensional array like:
public static int[][] transpose (int[][] original) {
int[][] array = new int[original.length][];
// transpose
if (original.length > 0) {
for (int i = 0; i < original[0].length; i++) {
array[i] = new int[original[i].length];
for (int j = 0; j < original.length; j++) {
array[i][j] = original[j][i];
}
}
}
return array;
}
and then call it as:
System.out.print(Arrays.toString(test.minrow(transpose(array))));
Or, if you want to go without transpose, this is how you can do:
public static int[] mincol (int[][] n) {
int[] result = new int[n.length];
for (int i = 0; i < n.length; i++) {
int min = n[0][i];
for (int j = 0; j < n[0].length; j++) {
if (n[j][i] < min) {
min = n[j][i];
}
}
result[i] = min;
}
return result;
}
Your for loop looks ok. Check the code below I fixed some minor issues.
Based on your code replace Class code with below:
public class Test {
public static void main(String[] args) {
int[][]array={{6,1,9}, {0,1,2}, {3,7,5}};
int[] test;
test = minrow(array);
for(int i=0; i<test.length; i++){
System.out.println(test[i]);
}
}
public static int[] minrow(int[][] n){
int [] result = new int[n.length];
int min;
for(int i=0;i<n.length;i++){
min=0;
for(int j=0;j<n[i].length;j++){
if(n[i][j]<n[i][min]){
min=j;
}
}
result[i]=n[i][min];
}
return result;
}
}
How do you sort an arraylist using insertion? Here is my arraylist it is filled with random Integers:
ArrayList<Integer> oh = new ArrayList<Integer>();
Random random = new Random();
for (int i = 0; i < 100; i++)
{
oh.add(random.nextInt());
}
Try this can help you to solve problem, sorting Arraylist with insertion sort.
public static void main(String args[]) {
ArrayList<Integer> oh = new ArrayList<Integer>();
Random random = new Random();
for (int i = 0; i < 100; i++) {
oh.add(random.nextInt());
}
int[] elementlist = new int[oh.size()];
Iterator<Integer> iter = oh.iterator();
for (int j = 0; iter.hasNext(); j++) {
elementlist[j] = iter.next();
}
int[] list = insertionSort(elementlist);
for (Integer in : list) {
System.out.println(in);
}
}
public static int[] insertionSort(int[] list) {
for (int i = 1; i < list.length; i++) {
int next = list[i];
// find the insertion location while moving all larger element up
int j = i;
while (j > 0 && list[j - 1] > next) {
list[j] = list[j - 1];
j--;
}
// insert the element
list[j] = next;
}
return list;
}
For more info go in link
import java.util.ArrayList;
public class InsertionSort {
private static ArrayList<Integer> inputArray = new ArrayList<Integer>();
public static ArrayList<Integer> getInputArray() {
return inputArray;
}
public InsertionSort(ArrayList<Integer> inputArray){
InsertionSort.inputArray = inputArray;
}
public void sortGivenArray(){
for(int i=1;i<inputArray.size();i++){
int key = inputArray.get(i);
for(int j= i-1;j>=0;j--){
if(key<inputArray.get(j)){
inputArray.set(j+1,inputArray.get(j));
if(j==0){
inputArray.set(0, key);
}
}else{
inputArray.set(j+1,key);
break;
}
}
}
}
}
import java.util.ArrayList;
import daa.InsertionSort;
public class MainPractise implements Cloneable {
public static void main(String[] args) {
ArrayList<Integer> unsortedArray = new ArrayList<Integer>();
unsortedArray.add(8);
unsortedArray.add(7);
unsortedArray.add(6);
unsortedArray.add(5);
unsortedArray.add(4);
unsortedArray.add(0);
unsortedArray.add(2);
InsertionSort is = new InsertionSort(unsortedArray);
System.out.println("---------Initial Unsorted Array---------");
for(int i:InsertionSort.getInputArray()){
System.out.print(i+" ");
}
is.sortGivenArray();
System.out.println("\n------------Sorted Array------------");
for(int i:InsertionSort.getInputArray()){
System.out.print(i+" ");
}
}
}
import java.util.ArrayList;
import java.util.Random;
public class Merge {
private static ArrayList<Integer> newArrayList;
public static ArrayList<Integer> generateArray(int n){
newArrayList = new ArrayList<Integer>(n);
Random rand = new Random();
for (int i = 0; i<n; i++){
newArrayList.add(rand.nextInt(n + 1));
}
return newArrayList;
}
public static ArrayList<Integer> mergeSort(ArrayList<Integer> x){
if (x.size()>1){
ArrayList<Integer> ArrayList1 = new ArrayList<Integer>(x.size()/2);
ArrayList<Integer> ArrayList2 = new ArrayList<Integer>(x.size()-(x.size()/2));
for (int i = 0; i<newArrayList.size()/2; i++){
ArrayList1.set(i, newArrayList.get(i));
}
for (int i = (newArrayList.size()/2); i<((newArrayList.size()/2)+(newArrayList.size()-newArrayList.size()/2)); i++){
ArrayList2.set(i-(newArrayList.size()/2), newArrayList.get(i));
}
//ArrayList1 = mergeSort(ArrayList1);
//ArrayList2 = mergeSort(ArrayList2);
int j = 0;
int k = 0;
int a = 0;
while(ArrayList1.size() != j && ArrayList2.size() != k){
if (ArrayList1.get(j) < ArrayList2.get(k)){
x.set(a, ArrayList1.get(j));
a++;
j++;
} else {
x.set(a, ArrayList2.get(k));
a++;
k++;
}
}
while (ArrayList1.size()!=j){
x.set(a, ArrayList1.get(j));
a++;
j++;
}
while (ArrayList2.size()!=k){
x.set(a, ArrayList2.get(k));
a++;
k++;
}
}
return x;
}
public static void main(String[] args) {
// TODO Auto-generated method stub
ArrayList<Integer> new1;
//ArrayList<Integer> new2;
//ArrayList<Integer> new3;
new1 = generateArray(10);
//new2 = generateArray(100);
//new3 = generateArray(1000);
System.out.println(new1);
mergeSort(new1);
System.out.println(new1);
}
}
I am attempting to implement a mergeSort method but I keep getting the following error:
Exception in thread "main" java.lang.IndexOutOfBoundsException: Index: 0, Size: 0
at java.util.ArrayList.RangeCheck(ArrayList.java:547)
at java.util.ArrayList.set(ArrayList.java:337)
at Merge.mergeSort(Merge.java:23)
at Merge.main(Merge.java:73)
Any ideas?
You are attempting to set a position that doesn't exist yet in your ArrayList called ArrayList1. You've set the initial capacity to x.size() / 2, but there's nothing in it yet.
It looks like you are attempting to set each position, starting with position 0, so just add the elements instead. Replace
for (int i = 0; i<newArrayList.size()/2; i++){
ArrayList1.set(i, newArrayList.get(i));
}
with
for (int i = 0; i<newArrayList.size()/2; i++){
ArrayList1.add(newArrayList.get(i));
}
And you'll need to make similar changes to the for loop after that, which populates ArrayList2.