Skip to content

Instantly share code, notes, and snippets.

@pCYSl5EDgo
Created March 3, 2019 06:51
Show Gist options
  • Save pCYSl5EDgo/7fd40092d4f5a8337fb1c11daaaa66cc to your computer and use it in GitHub Desktop.
Save pCYSl5EDgo/7fd40092d4f5a8337fb1c11daaaa66cc to your computer and use it in GitHub Desktop.
そもそもこの手のものはstaticメソッドにするべきだと思います。
using System;
using UnityEngine;
public sealed class NameIncidenceTuple : UnityEngine.Object, IEquatable<NameIncidenceTuple>, IComparable<NameIncidenceTuple>
{
[SerializeField] public string Name;
[SerializeField] public int Incidence;
public override bool Equals(object other) => Equals(other as NameIncidenceTuple);
public bool Equals(NameIncidenceTuple other) => !(other is null) && Incidence == other.Incidence && Name == other.Name;
public int Compare(object other) => Compare(other as NameIncidenceTuple);
public int Compare(NameIncidenceTuple other)
{
if(other is null) return -1;
if(Incidence == other.Incidence) return Name.Compare(other.Name);
return - other.Incidence + Incidence; // 発生確率の大きいものを先頭にする
}
}
public sealed class SetIncidenceSample : MonoBehaviour
{
[SerializeField] public NameIncidenceTuple[] Pairs;
private int Sum;
int CalcGCD(int a, int b) => b == 0 ? a : GCD(b, a % b);
void Start()
{
Array.Sort(Pairs);
var GCD = Pairs[i].Incidence;
for(int i = 1; i < Pairs.Length; i++)
{
if(GCD <= 1) break;
var incidence = Pairs[i].Incidence;
if(incidence == GCD)
continue;
if(incidence < GCD)
GCD = CalcGCD(GCD, incidence);
else
GCD = CalcGCD(incidence, GCD);
}
Sum = 0;
for(int i = 0; i < Pairs.Length; i++)
{
Sum += Pairs[i].Incidence / GCD;
}
}
public string GetMonsterNameRandom()
{
var random = UnityEngine.Random.Range(0, Sum);
//しきい値を超えるインデックスを探します
int threshold = 0;
for (int i = 0; i < Pairs.Length; i++)
{
threshold += Pairs[i].Incidence;
if (random <= threshold)
{
return Pairs[i].Name;
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment