mirror of
https://github.com/Lendaia/oe-alga-feladatok.git
synced 2026-04-23 04:16:32 +01:00
141 lines
3.7 KiB
C#
141 lines
3.7 KiB
C#
using System;
|
|
using System.ComponentModel;
|
|
using System.Linq;
|
|
using System.Runtime.InteropServices;
|
|
|
|
namespace OE.ALGA.Optimalizalas
|
|
{
|
|
public class HatizsakProblema
|
|
{
|
|
public int N { get; }
|
|
public int Wmax { get; }
|
|
public int[] W { get; }
|
|
public float[] P { get; }
|
|
public HatizsakProblema(int n, int wmax, int[] w, float[] p)
|
|
{
|
|
N = n;
|
|
Wmax = wmax;
|
|
if (w.Length == p.Length && p.Length == n)
|
|
{
|
|
W = w;
|
|
P = p;
|
|
}
|
|
}
|
|
public int OsszSuly(bool[] pakolas)
|
|
{
|
|
int osszsuly = 0;
|
|
for (int i = 0; i < N; i++)
|
|
{
|
|
if (pakolas[i])
|
|
{
|
|
osszsuly += W[i];
|
|
}
|
|
}
|
|
return osszsuly;
|
|
}
|
|
public float OsszErtek(bool[] pakolas)
|
|
{
|
|
float osszertek = 0;
|
|
if (pakolas.Length == N)
|
|
{
|
|
for (int i = 0; i < N; i++)
|
|
{
|
|
if (pakolas[i])
|
|
{
|
|
osszertek += P[i];
|
|
}
|
|
}
|
|
}
|
|
return osszertek;
|
|
}
|
|
public bool Ervenyes(bool[] pakolas)
|
|
{
|
|
return (OsszSuly(pakolas) <= Wmax);
|
|
}
|
|
}
|
|
public class NyersEro<T>
|
|
{
|
|
int m;
|
|
Func<int, T> generator;
|
|
Func<T, float> josag;
|
|
int lepesszam;
|
|
public int LepesSzam
|
|
{
|
|
get { return lepesszam; }
|
|
}
|
|
public NyersEro(int m, Func<int, T> generator, Func<T, float> josag)
|
|
{
|
|
this.m = m;
|
|
this.generator = generator;
|
|
this.josag = josag;
|
|
}
|
|
public T OptimalisMegoldas()
|
|
{
|
|
T legjobb = generator(1);
|
|
for (int i = 1; i < m; i++)
|
|
{
|
|
T tmp = generator(i);
|
|
if (josag(tmp) >= josag(legjobb))
|
|
{
|
|
legjobb = tmp;
|
|
}
|
|
lepesszam++;
|
|
}
|
|
return legjobb;
|
|
}
|
|
}
|
|
public class NyersEroHatizsakPakolas
|
|
{
|
|
int lepesszam;
|
|
public int LepesSzam
|
|
{
|
|
get { return lepesszam; }
|
|
}
|
|
HatizsakProblema problema;
|
|
public NyersEroHatizsakPakolas(HatizsakProblema problema)
|
|
{
|
|
this.problema = problema;
|
|
}
|
|
public bool[] Generator(int i)
|
|
{
|
|
int szam = i;
|
|
bool[] pakolas = new bool[problema.N];
|
|
for (int j = problema.N - 1; j >= 0; j--)
|
|
{
|
|
bool ertek = (szam % 2 != 0);
|
|
pakolas[j] = ertek;
|
|
if (ertek && szam > 0)
|
|
{
|
|
szam--;
|
|
}
|
|
szam = szam / 2;
|
|
}
|
|
return pakolas;
|
|
}
|
|
public float Josag(bool[] pakolas)
|
|
{
|
|
float ertek = 0;
|
|
if (!problema.Ervenyes(pakolas))
|
|
{
|
|
ertek = -1;
|
|
}
|
|
else
|
|
{
|
|
ertek = problema.OsszErtek(pakolas);
|
|
}
|
|
return ertek;
|
|
}
|
|
public bool[] OptimalisMegoldas()
|
|
{
|
|
NyersEro<bool[]> nyersero = new NyersEro<bool[]>(Convert.ToInt32(Math.Pow(2, Convert.ToDouble(problema.N))), Generator, Josag);
|
|
bool[] megoldas = nyersero.OptimalisMegoldas();
|
|
lepesszam = nyersero.LepesSzam;
|
|
return megoldas;
|
|
}
|
|
public float OptimalisErtek()
|
|
{
|
|
return problema.OsszErtek(OptimalisMegoldas());
|
|
}
|
|
}
|
|
}
|