Skip to content

Instantly share code, notes, and snippets.

@rvhuang
Last active March 31, 2017 14:22
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 rvhuang/2a8ad172201124463bff07d027ef0feb to your computer and use it in GitHub Desktop.
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
// 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