An output similar to the following code is expressed only by int type.

Asked 1 years ago, Updated 1 years ago, 265 views

The following two codes are represented by int type and String, but if you want to express similar output, what kind of code can you use if you write this r in int (all arguments are int type)?

public class Partitions {
    public static void main(String[]args) {
        partition(7,7,"");
    }

    public static void partition(inti, intn, Stringr) {
        if(n==0){
            System.out.println("{"+r+"}");
            return;
        }

        /*
           for(int j = Math.min(i,n); j>=1;j--){
           partition(j,n-j,j+(r.isEmpty()?":",")+r);
           }

         */

        if(i<n){
            for(int j=i;j>=1;j--){
                partition(j,n-j,j+(r.isEmpty()?":",")+r);
            }
        } else {
            for(int j=n;j>=1;j--){
                partition(j,n-j,j+(r.isEmpty()?":",")+r);
            }
        }
    }
}

java

2022-09-30 21:58

2 Answers

Why don't you consider the int variable to stack?

import java.util.stream.Collectors;
import java.util.stream.stream;
import java.util.stream.stream.Builder;

public class Partitions {
    public static void main(String[]args) {
        partition(7,7,0);
    }

    public static void partition(inti, intn, intr) {
        if(n==0){
            write(r);
            return;
        }

        if(i<n){
            for(int j=i;j>=1;j--){
                partition(j, n-j, push(r,j));
            }
        } else{
            for(int j=n;j>=1;j--){
                partition(j, n-j, push(r,j));
            }
        }
    }

    static void write (inter) {
        String numbers = stream(r).map(String::valueOf).collect(Collectors.joining(","));
        System.out.println("{"+number+"}");
    }

    static int push (intr, intj) {
        return(r<<3)|j;
    }

    static Stream<Integer>stream(inter){
        Builder<Integer>ret=Stream.builder();
        while(r>0){
            intv=r&0x7;
            ret.add(v);
            r=r>>>3;
        }
        return ret.build();
    }
}


2022-09-30 21:58

The argument r will not be required.

import java.util.ArrayList;
import java.util.List;

public class Partitions {
  public static void main(String[]args) {
    partition(7,7).forEach(System.out:println);
  }

  public static List<List<Integer>>partition(inti, intn){
    List<List<Integer>>result=new ArrayList<List<Integer>>();

    if(n==0){
      result.add(new ArrayList<Integer>());
      return result;
    }

    for(int j = Math.min(i,n); j>0;j--){
      for(List<Integer>row:partition(j,n-j)){
        row.add(j);result.add(row);
      }
    }

    return result;
  }
}

// execution result
[7]
[1, 6]
[2, 5]
[1, 1, 5]
[3, 4]
[1, 2, 4]
[1, 1, 1, 4]
[1, 3, 3]
[2, 2, 3]
[1, 1, 2, 3]
[1, 1, 1, 1, 3]
[1, 2, 2, 2]
[1, 1, 1, 2, 2]
[1, 1, 1, 1, 1, 2]
[1, 1, 1, 1, 1, 1, 1]


2022-09-30 21:58

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.