Last active
March 31, 2017 14:22
-
-
Save rvhuang/2a8ad172201124463bff07d027ef0feb to your computer and use it in GitHub Desktop.
The source code of Coins Flipping AI live demo running on Azure Functions
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// https://rvhuang.github.io/livedemo/coinsflipping.html | |
#r "..\Shared\AlgorithmForce.HeuristicSuite.Portable.dll" | |
using System; | |
using System.Collections.Generic; | |
using System.Net; | |
using System.Web.Http; | |
using AlgorithmForce.HeuristicSuite; | |
public static IEnumerable<bool[]> Run(Request req, TraceWriter log) | |
{ | |
log.Info("C# HTTP trigger function processed a request."); | |
if (req == null || req.Coins == null || req.Coins.Length != 10) | |
throw new HttpResponseException(HttpStatusCode.BadRequest); | |
var init = req.Coins; | |
var goal = new bool[10] { true, true, true, true, true, true, true, true, true, true, }; | |
// https://github.com/rvhuang/heuristic-suite/blob/master/AlgorithmForce.HeuristicSuite/AStar.cs | |
var engine = new AStar<bool[]>(); | |
// https://github.com/rvhuang/heuristic-suite/blob/master/AlgorithmForce.HeuristicSuite/SequenceEqualityComparer.cs | |
engine.EqualityComparer = new SequenceEqualityComparer<bool>(); | |
engine.NextStepsFactory = GetNextSteps; | |
var solution = engine.Execute(init, goal, new PuzzleStateComparer()).Reverse(); | |
foreach (var step in solution.Enumerate()) | |
yield return step.Key; | |
} | |
public static IEnumerable<Step<bool[]>> GetNextSteps(Step<bool[]> step) | |
{ | |
for (var i = 0; i < step.Key.Length - 1; i++) | |
{ | |
var copied = step.Key.ToArray(); | |
copied[i] = !copied[i]; | |
copied[i + 1] = !copied[i + 1]; | |
yield return new Step<bool[]>(copied); | |
} | |
} | |
public class Request | |
{ | |
public bool[] Coins { get; set; } | |
} | |
public class PuzzleStateComparer : HeuristicComparer<bool[]> | |
{ | |
public PuzzleStateComparer() | |
: base(Estimation) | |
{ | |
// https://github.com/rvhuang/heuristic-suite/blob/master/AlgorithmForce.HeuristicSuite/HeuristicComparer.cs | |
} | |
private static double Estimation(bool[] coins) | |
{ | |
// State with higher score will be prioritized by the queue. | |
return 0 - (coins.Count(coin => coin) + GetContinuity(coins)); | |
} | |
private static int GetContinuity(bool[] coins) | |
{ | |
var finalScore = 0; | |
var currentScore = 0; | |
for (var i = 0; i < coins.Length - 1; i++) | |
{ | |
if (coins[i] && coins[i + 1]) | |
currentScore += 1; | |
else | |
{ | |
if (finalScore < currentScore) | |
finalScore = currentScore; | |
currentScore = 0; | |
} | |
} | |
if (finalScore < currentScore) | |
finalScore = currentScore; | |
return finalScore; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment