C# 转成java 一个算法

lele_nancy 2014-06-11 03:18:54
第一次写java,C#的程序写好了,搞了一天还是做不出来,各位帮忙。



class Program
{
static int iData = 0;
static int iGetLen = 0;
static StringBuilder sb = new StringBuilder();
static Dictionary<int, List<string>> dicNums = new Dictionary<int, List<string>>();
static int SetLen = 0;
static void Main(string[] args)
{
int n;
while (int.TryParse(Console.ReadLine(), out n) == false)
{

}
SetLen = n;
DateTime startDt = DateTime.Now;

PrintData(SetLen);
TimeSpan ts = DateTime.Now - startDt;
Console.WriteLine(ts.TotalMilliseconds);
//Console.Read();
//if (iData == iGetLen)
//{
foreach (KeyValuePair<int, List<string>> kvp in dicNums)
{
foreach (string strdata in kvp.Value)
{
Console.WriteLine(strdata);
}
}
Console.WriteLine(string.Format("N({0}) = {0} * ({0} -1) +1)", n));
//}
//else
//{ Console.WriteLine("解答不可"); }
ts = DateTime.Now - startDt;
Console.WriteLine(ts.TotalMilliseconds );
Console.Read();

}


private static void PrintData(int iLen)
{
iData = iLen * (iLen - 1) + 1;
var b = new int[iLen];
var C = new List<int>();
for(int i = 1;i<= iLen ;i++)
{
b[i-1] = i;
C.Add(i);
}
for (int j = 1; j <= iLen; j++)
{
WriteCombinations<int>(b, j);
}
}

static void WriteCombinations<T>(T[] array, int length)
{
var combinations = new Combinations<T>(array, length);
List<string> lstNum = new List<string>();
foreach (var oneCom in combinations)
{
//if (Utility.CheckData<T>(oneCom) == false) continue;
string strData = Utility.GetString<T>(oneCom);
//Console.WriteLine(strData);
lstNum.Add(strData);
}
dicNums.Add(length, lstNum);
iGetLen += lstNum.Count;
//Console.WriteLine(combinations.ToString());
//Console.WriteLine();
}



public static class Utility
{
/// <summary>
/// IList(T)の要素を文字列化したものすべてを連結した文字列を取得します。
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="list"></param>
/// <returns></returns>
public static string GetString<T>(IList<T> list)
{
var sb = new StringBuilder();
var isum = 0;
foreach (T item in list)
{
sb.Append(item.ToString() + "+");
isum += Convert.ToInt32(item);
}

if (sb.Length > 0) sb.Remove(sb.Length - 1, 1);
sb.Append("=" + isum.ToString());
return sb.ToString();
}
}

public class Combinations<T>
{
#region メンバ
private IList<T> _items;
private int _length;
private List<IList<T>> _combinations;
private int[] _finalIndices;
#endregion

#region コンストラクタ
public Combinations(IList<T> items) : this(items, items.Count) { }
public Combinations(IList<T> items, int select)
{
if (select < 0)
throw new ArgumentException("選択要素数は、0以上でなくてはなりません。");
if (items.Count < select)
throw new ArgumentException("選択要素数は、対象要素数以下でなくてはなりません。");

_items = items;
_length = select;
_combinations = new List<IList<T>>();

if (select == 0) return;

_finalIndices = GetFinalIndices(select);
ComputeCombination();
}
#endregion

/// <summary>
/// 選択要素数に応じた組み合わせとなる最後の値を取得します。(終端の確定)
/// </summary>
/// <param name="select"></param>
/// <returns></returns>
private int[] GetFinalIndices(int select)
{
var finalindices = new int[select];

int j = select - 1;
for (var i = _items.Count - 1; i > _items.Count - 1 - select; i--)
{
finalindices[j] = i;
j--;
}
return finalindices;
}

#region プロパティ
/// <summary>
/// 組み合わせの要素数を取得します。
/// </summary>
public int Count
{
get { return _combinations.Count != 0 ? _combinations.Count : 1; }
}
#endregion

/// <summary>
/// 条件をもとに組み合わせを求めます。
/// </summary>
private void ComputeCombination()
{
if (_finalIndices.Length == 0) return;

var indices = Enumerable.Range(0, _length).ToArray();
_combinations.Add(GetCurrentCombination(indices));

//while (NextCombination(indices))
//{
// _combinations.Add(GetCurrentCombination(indices));
//}
while (indices[0] != _finalIndices [0])
{
if (NextCombination(indices))
_combinations.Add(GetCurrentCombination(indices));
}
}

/// <summary>
/// 現在の組み合わせを取得します。
/// </summary>
/// <param name="indices"></param>
/// <returns></returns>
private T[] GetCurrentCombination(int[] indices)
{
T[] oneCom = new T[_length];
for (var k = 0; k < _length; k++)
{
oneCom[k] = _items[indices[k]];
}
return oneCom;
}

/// <summary>
/// 次の組み合わせへ
/// </summary>
/// <param name="indices"></param>
/// <returns></returns>
private bool NextCombination(int[] indices)
{
for (var j = _finalIndices.Length - 1; j > -1; j--)
{
if (indices[j] < _finalIndices[j])
{
indices[j]++;
for (var k = 1; j + k < _finalIndices.Length; k++)
{
indices[j + k] = indices[j] + k;
}
//if (indices[j] == _finalIndices[j])
break;
}
if (j == 0) return false;
}
List<List<int>> isUnable = indices.Aggregate(
new List<List<int>>(), // TAccumulate(集計結果)の初期化
(accumulate, value) =>
{
if (accumulate.Count == 0)
{
accumulate.Add(new List<int>() { value });
}
else
{
var currentList = accumulate.Last();
var preValue = currentList.Last();
if (value - preValue == 1)
{
currentList.Add(value);
}
else
{
accumulate.Add(new List<int>() { value });
}
}

return accumulate;
});
//.Select(l => string.Join(", ", l))
//.ToList().ForEach(x => Console.WriteLine(x));
if (isUnable.Count > 2)
{
return false;
}
else if (isUnable.Count == 2)
{
if (isUnable[0].First() == 0 && isUnable[1].Last() == (_items.Count-1))
return true;
else
return false;
}
else { return true; }
}

/// <summary>
/// イテレータ
/// </summary>
/// <returns></returns>
public IEnumerator<IList<T>> GetEnumerator()
{
foreach (var item in _combinations) yield return item;
}

/// <summary>
/// ToString
/// </summary>
/// <returns></returns>
public override string ToString()
{
return string.Format("{0}C{1} Of [{2}] - {3}通り"
, _items.Count
, _length
, Utility.GetString<T>(_items)
, this.Count);
}

}
}


...全文
195 6 打赏 收藏 转发到动态 举报
写回复
用AI写文章
6 条回复
切换为时间正序
请发表友善的回复…
发表回复
tony4geek 2014-06-20
  • 打赏
  • 举报
回复
没看出来什么规律怎么生成的。
lele_nancy 2014-06-11
  • 打赏
  • 举报
回复
引用 2 楼 rui888 的回复:
写好了???
没有,不会啊,java
lele_nancy 2014-06-11
  • 打赏
  • 举报
回复
问题是要求一个队列
排列组合的 个数满足 N *(N-1) +1
4 * 3 + 1 = 13
1=1
2=2
3=3
4=4
1+2=3
1+4=5
2+3=5
3+4=7
1+2+3=6
1+2+4=7
1+3+4=8
2+3+4=9
1+2+3+4=10

刚好13组

lele_nancy 2014-06-11
  • 打赏
  • 举报
回复
问题是要求一个队列
排列组合的 个数满足 N *(N-1) +1
4 * 3 + 1 = 13
1=1
2=2
3=3
4=4
1+2=3
1+4=5
2+3=5
3+4=7
1+2+3=6
1+2+4=7
1+3+4=8
2+3+4=9
1+2+3+4=10

刚好13组

tony4geek 2014-06-11
  • 打赏
  • 举报
回复
写好了???
lele_nancy 2014-06-11
  • 打赏
  • 举报
回复
Java

import java.io.*;
import java.util.*;
import java.lang.*; 
import java.util.Enumeration; 

public class LingNum
{
    static int iData = 0;
    static int iGetLen = 0;
    static StringBuilder sb = new StringBuilder();
    static Map<Object, IList<String>> dicNums = new HashMap<Object, IList<String>>();
    static int SetLen = 0;
    static Combinations combinations ;
    static IList<String> lstNum ;
    static void Main(String[] args)
        {
            int n;
            Console console = System.console();
            String line = console.readLine("入力 %d: ");
            while ( Integer.parseInt(line)<0)
            {
                line = console.readLine("入力 %d: ");
            }
            n = Integer.parseInt(line);
            SetLen = n;
            long startDt = System.currentTimeMillis();
            PrintData(SetLen);
            long endDt = System.currentTimeMillis();
                        
            System.out.println(endDt- startDt);
            //Console.Read();
            //if (iData == iGetLen)
            //{
                for (Map.Entry<Object, IList<String>> kvp : dicNums.entrySet())
                {
                    for (Object strdata : kvp.getValue())
                    {
                        System.out.println(strdata.toString());
                    }
                }
                System.out.println(String.format("N(%d) = %d * (%d -1) +1)", n,n,n));
            //}
            //else
            //{ System.out.println("解答不可"); }
            endDt = System.currentTimeMillis();
            System.out.println(endDt- startDt);
            console.readLine();
            
        }
        private static void PrintData(int iLen)
        {
            iData = iLen * (iLen - 1) + 1;
            IList<int> b = new IList<int>();
            //var C = new List<int>();
            for(int i = 1;i<= iLen ;i++)
            {
                b.add(i-1, i);
                //C.Add(i);
            }
            for (int j = 1; j <= iLen; j++)
            {
                WriteCombinations(b, j);
            }
        }

        private static <T> void WriteCombinations(IList<T> array, int length)
        {
            combinations = new Combinations(array, length);
            lstNum = new IList<String>();
            for (Object oneCom : combinations._combinations)
            {
                //if (Utility.CheckData<T>(oneCom) == false) continue;
                String strData = Utility.<IList<T>>GetString(oneCom);
                //System.out.println(strData);
                lstNum.add(lstNum.size,strData);
                iGetLen += 1;
            }
            dicNums.put(length, lstNum);
            
            //System.out.println(combinations.ToString());
            //System.out.println();
        }

        

        public static class Utility
        {
             public static <T> String GetString(IList<T> list)
            {
                StringBuilder sb = new StringBuilder();
                int isum = 0;
                for (T item : list)
                {
                    sb.append(item.toString() + "+");
                    isum += Integer.parseInt(item.toString());
                }

                if (sb.length() > 0) sb.deleteCharAt(sb.length()-1) ;
                sb.append("=" + isum);
                return sb.toString();
            }
        }

        public class Combinations<T>
        {
            public IList<T> _items;
            private int _length;
            public IList<IList<T>> _combinations;
            private int[] _finalIndices;

            public <T>Combinations(IList<T> items) 
            {
                this(items, items.size);
            }
            public <T> Combinations(IList<T> items, int select)
            {
                if (select < 0)
                    throw new IllegalArgumentException("選択要素数は、0以上でなくてはなりません。");
                if (items.size < select)
                    throw new IllegalArgumentException("選択要素数は、対象要素数以下でなくてはなりません。");

                _items = items;
                _length = select;
                _combinations = new IList<IList<T>>();

                if (select == 0) return;
                _finalIndices = GetFinalIndices(select);
                ComputeCombination();
            }

            private int[] GetFinalIndices(int select)
            {
                int[] finalindices = new int[select];

                int j = select - 1;
                for (int i = _items.size - 1; i > _items.size - 1 - select; i--)
                {
                    finalindices[j] = i;
                    j--;
                }
                return finalindices;
            }

            public int Count()
            {
                 return (_combinations.size != 0 ? _combinations.size : 1); 
            }
           private void ComputeCombination()
            {
                if (_finalIndices.length == 0) return;

                int[] indices;
                for(int i= 1; i<= _length; i++)
                {
                    indices[i-1] = i-1;
                }
                _combinations.add(0,GetCurrentCombination(indices));

               while (indices[0] != _finalIndices [0])
                {
                    if (NextCombination(indices))
                        _combinations.add(_combinations.size,GetCurrentCombination(indices));
                }
            }

          private IList<T> GetCurrentCombination(int[] indices)
            {
                IList<T> oneCom = new IList<T>();
                for (int k = 0; k < _length; k++)
                {
                    oneCom.set(k, _items.get(indices[k]));
                }
                return oneCom;
            }

           private boolean NextCombination(int[] indices)
            {
                for (int j = _finalIndices.length - 1; j > -1; j--)
                {
                    if (indices[j] < _finalIndices[j])
                    {
                        indices[j]++;
                        for (int k = 1; j + k < _finalIndices.length; k++)
                        {
                            indices[j + k] = indices[j] + k;
                        }
                        //if (indices[j] == _finalIndices[j])
                        break;
                    }
                    if (j == 0) return false;
                }
                IList<IList<int>> isUnable = indices.Aggregate(
                   new IList<IList<int>>(),    // TAccumulate(集計結果)の初期化
                   (accumulate, value) ->
                   {
                       if (accumulate.Count == 0)
                       {
                           accumulate.add(new IList<int>((Arrays.asList(value))));
                       }
                       else
                       {
                           var currentList = accumulate.get(accumulate.size()-1);
                           var preValue = currentList.get(currentList.size()-1);
                           if (value - preValue == 1)
                           {
                               currentList.add(value);
                           }
                           else
                           {
                               accumulate.add(new ArrayList<int>((Arrays.asList(value))));
                           }
                       }

                       return accumulate;
                   });
                    //.Select(l => String.Join(", ", l))
                    //.ToList().ForEach(x => System.out.println(x));
                if (isUnable.size > 2)
                {
                    return false; 
                }
                else if (isUnable.size == 2)
                {
                    if (Integer.parseInt(isUnable.get(0).get(0).toString()) == 0 && Integer.parseInt(isUnable.get(1).get(isUnable.get(1).size-1).toString()) == (_items.size-1))
                        return true;
                    else
                        return false;
                }
                else { return true; }
            }

         public String ToString()
            {
                return String.format("{0}C{1} Of [{2}] - {3}通り"
                        , _items.size
                            , _length
                            , Utility.GetString(_items)
                            , this.Count());
            }

        }
public class IList<E> implements Iterable {
    Node head,tail;
    public int size;
    public IList () {
	head = new Node();
	tail = new Node();
	head.next = tail;
	tail.prev = head;
	head.prev = tail.next = null;
	size = 0;
    }
    public E get(int i) {
	Node tmp = head.next;
	for (int j=0; j<i;j++) {
	    tmp = tmp.next;
	}
	return tmp.e;
    }
    public E set(int i, E e){
	Node tmp = head.next;
	for (int j=0; j<i;j++) {
	    tmp = tmp.next;
	}
	E d = tmp.e;
	tmp.e = e;
	return d;
    }
    public void add(int i, E e){
	Node tmp = head.next;
	for (int j=0; j<i;j++) {
	    tmp = tmp.next;
	}
	Node n = new Node();
	n.e = e;
	n.prev = tmp.prev;
	n.next = tmp;
	tmp.prev.next = n;
	tmp.prev = n;
    }
    public void remove(int i){
	Node tmp = head.next;
	for (int j=0; j<i;j++) {
	    tmp = tmp.next;
	}
	tmp.prev.next = tmp.next;
	tmp.next.prev = tmp.prev;
    }
    class Node {
	Node prev, next;
	E e;
    }
    public void print() {
	Node tmp = head.next;
	while(tmp != tail) {
	    System.out.println(tmp.e);
	    tmp = tmp.next;
	}
    }
    protected Node getNode() {
	return new Node();
    }
    public ListIterator<E> iterator () {
	ListIterator<E> i = new ListIterator<E>(this);
	return i;
    }
}

}

62,614

社区成员

发帖
与我相关
我的任务
社区描述
Java 2 Standard Edition
社区管理员
  • Java SE
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧