Skip to content

Instantly share code, notes, and snippets.

@sarukun99
Last active August 15, 2018 01:29
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save sarukun99/3e11a08c9b9aef0e07164fcf47bcff88 to your computer and use it in GitHub Desktop.
Save sarukun99/3e11a08c9b9aef0e07164fcf47bcff88 to your computer and use it in GitHub Desktop.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System.Linq;
public class TextPredicator {
public static void Predicate(List<string> search, List<List<string>> choices)
{
//全ての候補の転置インデックスを作成する
var indexs = choices.Select(choice => new InversedIndex(choice));
// 初期のPathを作成する
var paths = new List<Path>();
for (int i = 0; i < search.Count; i++)
{
foreach (var index in indexs)
{
var nodes = index.Positions(search[i]);
foreach (var node in nodes)
{
paths.Add(new Path(index, node, i));
}
}
}
// Searchの全文字列を各Pathに渡して更新する
for (int i = 0; i < search.Count; i++)
{
foreach (var path in paths)
{
path.Select(i, search[i]);
}
}
//一番スコアの高いパスを採択
var selectedChoice = paths.OrderByDescending(Path => Path.Score()).First().Source();
Debug.Log(selectedChoice);
}
class InversedIndex {
public string source;
public InversedIndex(List<string> source) {
for (var i = 0; i < source.Count(); i ++ ) {
var key = source[i];
if (dict.ContainsKey(key) == false)
{
dict[key] = new List<int>();
}
dict[key].Add(i);
}
this.source = string.Join("", source.ToArray());
}
public int[] Positions(string s) {
if (dict.ContainsKey(s) == false ) {
return new int[] {};
} else {
return dict[s].ToArray();
}
}
private Dictionary<string, List<int>> dict = new Dictionary<string, List<int>>();
}
class Path {
public Path(InversedIndex index, int node, int pos){
mPos = pos;
mNodes.Add(node);
mIndex = index;
}
public void Select(int pos, string s) {
if (pos < mPos) { return; }
var newPos = mIndex.Positions(s)
.Where(p => mPos < pos)
.OrderBy(p => pos - mPos)
.FirstOrDefault();
if (newPos > 0)
{
mNodes.Add(newPos);
} else {
mNodes.Add(-1);
}
}
public float Score() {
return mNodes.Where(node => node > -1).Count() / mIndex.source.Length;
}
public string Source() {
return mIndex.source;
}
private InversedIndex mIndex;
private List<int> mNodes = new List<int>();
private int mPos = 0;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment