【发布时间】:2015-11-23 03:03:51
【问题描述】:
我正在尝试解决问题 24 https://projecteuler.net/problem=24 euler 项目的我和我在这个问题上花了很多时间但仍然没有成功。
但现在不是问题了,我想知道我的方法有什么问题。
我正在使用简单的排列来获取最左边的数字并从要找到的术语中获取剩余值(通过减法,即使用模运算符)。
Java 代码:
import java.util.ArrayList;
public class LexOrder
{
public static int factorial(int num)
{
int res=1;
if(num <= 1)
return 1;
while(num > 1)
{
res *= num--;
}
return res;
}
public static ArrayList<Integer> addValue(int digit, ArrayList<Integer> al)
{
int temp=0, count=0;
while( count <= digit )
{
if( al.contains(count) )
temp++;
count++;
}
int val = digit+temp;
//checking weather the new number exists in the ArrayList or not.
while(true)
{
if(! al.contains(val) )
{
al.add(val);
break;
}
else
{
val++;
}
}
return al;
}
public static void main(String args[])
{
ArrayList<Integer> al = new ArrayList<Integer>();
int index = 999999;
int numOfDigit = 10;
if( factorial( numOfDigit ) > index && index >= 0)
{
System.out.println("Index Validated");
}
else
{
System.out.println("Index out of bounds");
System.exit(0);
}
int digit, count=1;
while( index !=0 )
{
digit = ( index / factorial( numOfDigit - count ) );
al = addValue(digit, al);
index = ( index % factorial( numOfDigit - count ) );
if(index == 0)
break;
count++;
}
// Adding value in ascending order.
int temp =0;
while( al.size() < numOfDigit )
{
if(!al.contains(temp))
al.add(temp);
temp++;
}
System.out.println(al);
}
}
输出: [2, 7, 8, 3, 9, 1, 4, 5, 6, 0]
输出应该是: 2783915460
【问题讨论】:
标签: java functional-programming permutation