[英]Program to find smallest permutation of a number n1 but should be larger than another given number n2; print “Invalid” if not possible
The problem deals with two input integers. 问题涉及两个输入整数。 We need to find permutation of n1 such that it's smallest greater integer to n2.
我们需要找到n1的排列,使它成为n2的最小整数。
I have tried coding but I am not getting the correct output. 我已经尝试编码,但是没有得到正确的输出。 I can't figure out how to print only the smallest permutation larger than n2.
我不知道如何只打印大于n2的最小排列。 My code is printing all permutations larger than n2.
我的代码正在打印所有大于n2的排列。
My Code: 我的代码:
import java.util.*;
class kbc{
public static void main (String args[]) throws Exception {
int n1=124;
int n2=320;
String s1 = "";
s1+= n1;
String s2 = "";
s2+= n2;
if(s2.length()>s1.length())
System.out.println("Invalid");
else{
int[] ad = new int[s1.length()];
for (int i=0; i<s1.length();i++){
ad[i]= s1.charAt(i)-'0';
}
printSmallest(ad,n2,0);
}
}
static void printSmallest(int[] a, int n2, int k)
{
int snum;
int saved= Integer.MAX_VALUE;
String s="";
if (k == a.length)
{
for (int i = 0; i < a.length; i++)
{
s=s+a[i];
}
snum = Integer.parseInt(s);
if(snum>n2){
if(snum<saved){
saved=snum;
}
System.out.println(saved);
}
}
else{
for (int i = k; i < a.length; i++){
int temp = a[k];
a[k] = a[i];
a[i] = temp;
printSmallest(a,n2, k + 1);
temp = a[k];
a[k] = a[i];
a[i] = temp;
}
}
}
}
Expected Output: 预期产量:
412
Code Output: 代码输出:
421
412
The way you are picking the characters for permutation, it is causing the problem. 您选择字符进行排列的方式会引起问题。 If you pick the characters at ascending order of their ASCII value then it will not be a problem.
如果按ASCII值的升序选择字符,则不会有问题。 After getting your desired number, you can tell the recursion that "OK, I have found my answer, Don't call again".
获得所需的号码后,您可以告诉递归“好,我已经找到答案了,不要再打电话了”。 You can check this code.
您可以检查此代码。 I changed your code not that much.
我没有对您的代码进行太多更改。
class kbc {
private static boolean taken[];
private static boolean found = false;
public static void main (String args[]) throws Exception {
int n1=124;
int n2=320;
String s1 = "";
s1+= n1;
String s2 = "";
s2+= n2;
if(s2.length()>s1.length())
System.out.println("Invalid");
else {
taken = new boolean[s1.length()];
char[] ad = new char[s1.length()];
char[] tempArray = s1.toCharArray();
Arrays.sort(tempArray);
s1 = new String(tempArray);
printSmallest(ad, s1, n2,0);
}
}
static void printSmallest(char[] a, String s1, int n2, int k)
{
if(found)
return;
int snum;
int saved= Integer.MAX_VALUE;
String s="";
if (k == a.length)
{
for (int i = 0; i < a.length; i++)
{
s=s+a[i];
}
snum = Integer.parseInt(s);
if(snum>n2){
if(snum<saved){
saved=snum;
found = true;
}
System.out.println(saved);
}
}
else{
for (int i = 0; i < a.length; i++){
if(!taken[i] && !found) {
taken[i] = true;
a[k] = s1.charAt(i);
printSmallest(a, s1, n2, k + 1);
taken[i] = false;
}
}
}
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.