PlotDirector/PlotLine/Services/WritingSolverTraversal.cs

26 lines
1.3 KiB
C#

using PlotLine.Models.WritingSolver;
namespace PlotLine.Services;
// The queue contains unique semantic states. Duplicate answers with identical evidence
// must not consume the distinct-state budget before they are dequeued.
public static class WritingSolverTraversal
{
public static string Key(SolverOutcome outcome) => string.Join(",",outcome.Answers.Select(a=>a.Node))+":"+
string.Join(",",outcome.Scores.OrderBy(s=>s.Key).Select(s=>$"{s.Key}={s.Value}"))+":"+outcome.Next?.Id;
public static IEnumerable<SolverAnswer[]> Extensions(SolverOutcome outcome)
{
if(outcome.Next is not {} node)yield break;
foreach(var choice in node.Choices.Where(c=>c.Active))yield return [..outcome.Answers,new(node.Id,[choice.Id])];
if(!node.Multiple)yield break;
var substantive=node.Choices.Where(c=>c.Active && !c.Fallback).ToArray();
if(substantive.Length>12)throw new InvalidDataException("Split multi-select nodes with more than 12 substantive choices.");
for(var mask=1;mask<(1<<substantive.Length);mask++)
{
if((mask & (mask-1))==0)continue;
var ids=substantive.Where((_,i)=>(mask & (1<<i))!=0).Select(c=>c.Id).ToArray();
if(node.MaxChoices>0 && ids.Length>node.MaxChoices)continue;
yield return [..outcome.Answers,new(node.Id,ids)];
}
}
}