9: 2016-05-13 (金) 01:56:42 osinko |
10: 2016-06-18 (土) 00:31:03 osinko |
| 有用なデザインパターンをサンプルコードとして羅列したページ | | 有用なデザインパターンをサンプルコードとして羅列したページ |
| | | |
| + | |
| + | **帰納関数のサンプル(順列の出力) [#m9ded6a9] |
| + | |
| + | 基本的な帰納コードのサンプル |
| + | サンプルとして順列をテキストファイルで出力する |
| + | |
| + | <帰納処理を書くコツ> |
| + | -基底部、帰納部の二段階で関数を作成する(ドミノの一つ目、それに続く無限のドミノ、とふたつに分ける) |
| + | -基底の呼び出しの際は出来るだけ余計なデーターを渡さないように設計する |
| + | -派生する関数(帰納部)には「差が生じるデータ」を参照渡ししないようにする |
| + | -帰納関数の入口に終了条件を設定する |
| + | |
| + | #code(csharp){{ |
| + | using UnityEngine; |
| + | using System.Collections; |
| + | using System.Collections.Generic; |
| + | using System.IO; |
| + | |
| + | public class Perm : MonoBehaviour |
| + | { |
| + | void Start() |
| + | { |
| + | int length = 4; |
| + | char[] set = { 'A', 'B', 'C' }; |
| + | |
| + | List<string> strList = Root(set, length); |
| + | |
| + | string folder = Application.dataPath; //これだけでunityの実行ファイルがあるフォルダがわかる |
| + | SaveText(folder, @"\test6.txt", strList.ToArray()); |
| + | } |
| + | |
| + | //基底部 |
| + | List<string> Root(char[] set, int length) |
| + | { |
| + | List<string> strList = new List<string>(); |
| + | int level = 0; |
| + | |
| + | for (int i = 0; i < set.Length; i++) |
| + | { |
| + | char[] dat = new char[length]; |
| + | dat[0] = set[i]; |
| + | Loop(dat, level, set, strList); |
| + | } |
| + | |
| + | return strList; |
| + | } |
| + | |
| + | //帰納部 |
| + | void Loop(char[] dat, int level, char[] set, List<string> strList) |
| + | { |
| + | level++; |
| + | if (level < dat.Length) //帰納関数の終了条件 |
| + | { |
| + | for (int i = 0; i < set.Length; i++) |
| + | { |
| + | char[] cloneDat = (char[])dat.Clone(); //オブジェクトを複製する(帰納関数に参照渡ししないために大事な事!) |
| + | cloneDat[level] = set[i]; |
| + | Loop(cloneDat, level, set, strList); //複製したものを派生する帰納関数に渡すことが大事(それが差になる) |
| + | } |
| + | } |
| + | else { |
| + | strList.Add(new string(dat)); |
| + | } |
| + | } |
| + | |
| + | //資料:StreamWriter クラス (System.IO) |
| + | //http://msdn.microsoft.com/ja-jp/library/system.io.streamwriter(v=vs.110).aspx |
| + | |
| + | //テキストファイルとしてセーブ |
| + | public void SaveText(string fileFolder, string filename, string[] dataStr) |
| + | { |
| + | using (StreamWriter w = new StreamWriter(fileFolder + filename, false, System.Text.Encoding.GetEncoding("shift_jis"))) |
| + | { |
| + | foreach (var item in dataStr) |
| + | { |
| + | w.WriteLine(item); |
| + | } |
| + | } |
| + | } |
| + | } |
| + | }} |
| | | |
| **データーをwiki用に変換したりCSVで出力等 [#afbd5d39] | | **データーをwiki用に変換したりCSVで出力等 [#afbd5d39] |