2017年5月28日 星期日

Linear Regression(線性回歸)


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ConsoleApplication1
{
    class Program
    {
        static double AverageX = 0, AverageY = 0;
        static double Numerator = 0;
        static double Denominator = 0;
        static double RCB;
        static double RCA;
        static double Residual_SS = 0;
        static double Regression_SS = 0;

        static void Main(string[] args)
        {
            double[,] Point = new double[,]
            {
                {0, 67.37},
                {4, 71.0},
                {10, 76.3},
                {15, 80.6},
                {21, 85.7},
                {29, 92.9},
                {36, 99.4},
                {51, 110.6},
                {68, 126.1}
            };
            LinearRegression(Point);
            Console.Read();
        }       

        public static void LinearRegression(double[,] point)
        {
            if (point.GetLength(0) < 2)
            {
                Console.WriteLine("點的數量小於2,無法進行線性回歸");
                return;
            }           
            for (int i = 0; i < point.GetLength(0); i++)
            {
                AverageX += point[i, 0];
                AverageY += point[i, 1];
            }
            AverageX /= point.GetLength(0);
            AverageY /= point.GetLength(0);
            Console.WriteLine("平均X: {0}\n平均Y: {1}", AverageX, AverageY);          
            for (int i = 0; i < point.GetLength(0); i++)
            {
                Numerator += (point[i, 0] - AverageX) * (point[i, 1] - AverageY);
                Denominator += (point[i,0] - AverageX) * (point[i,0] - AverageX);
            }
            RCB = Numerator / Denominator;
            RCA = AverageY - RCB * AverageX;

            Console.WriteLine("回歸係數A " + RCA.ToString("0.0000"));
            Console.WriteLine("回歸係數B " + RCB.ToString("0.0000"));
            Console.WriteLine(string.Format("方程為: y = {0} + {1} * x",
                RCA.ToString("0.0000"), RCB.ToString("0.0000")));         
            for (int i = 0; i < point.GetLength(0); i++)
            {
                Residual_SS += (point[i, 1] - RCA - RCB * point[i, 0]) * (point[i, 1] - RCA - RCB * point[i, 0]);
                Regression_SS += (RCA + RCB * point[i, 0] - AverageY) * (RCA + RCB * point[i, 0] - AverageY);
            }
            Console.WriteLine("剩餘平方和: " + Residual_SS.ToString("0.0000"));
            Console.WriteLine("回歸平方和: " + Regression_SS.ToString("0.0000"));
        }
    }
}


K-means


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;

namespace SimpleKmean
{
    class Program
    {
        static int LoopCount = 1;
        static bool RecursiveFlag = false;
        static void Main(string[] args)
        {
            int[,] Nodes;
            int[,] Classes;
            System.Console.Write("how many nodes do you want? :");
          //  int NodeNumber = Convert.ToInt32(System.Console.ReadLine());
            int NodeNumber = 15;
            System.Console.Write("how many classes do you want? :");
         //   int ClassNumber = Convert.ToInt32(System.Console.ReadLine());
            int ClassNumber = 3;
            Nodes = new int[NodeNumber, 3]; // index -> x = 0 , y = 1 , classFlag = 3
            Classes = new int[NodeNumber, 2]; // classnumber coordinate , clustering coordinates
            Console.WriteLine();
           
            // get random coordinates
            //隨機產生15個點
            for (int i = 0; i < NodeNumber; i++)
            {               
                Random Random = new Random((int)DateTime.Now.Millisecond);
                Thread.Sleep(20);  //亂數的產生
                // get x
                Nodes[i, 0] = Random.Next(0, 10);              
                // get y
                Nodes[i, 1] = Random.Next(0, 10);
                System.Console.WriteLine("({0},{1})", Nodes[i, 0], Nodes[i, 1]);               
            }
            System.Console.WriteLine("-----------------");
           
            // get random class
            // 隨機產生class位置
            for (int i = 0; i < ClassNumber; i++)
            {
                Random random = new Random((int)DateTime.Now.Millisecond);
                Thread.Sleep(20);  //亂數的產生
                // get x
                Classes[i, 0] = random.Next(0, 10);               
                // get y
                Classes[i, 1] = random.Next(0, 10);
                System.Console.WriteLine("class[{0}]--({1},{2})", i, Classes[i, 0], Classes[i, 1]);
            }
            System.Console.WriteLine("---------------------------------------------------");
            Console.WriteLine("\n");

            Kmean(NodeNumber, ClassNumber, Nodes, Classes);           
            System.Console.WriteLine("=================================");
            System.Console.WriteLine("finish! recusive times : {0}", LoopCount);
           // ShowResult(Nodes, NodeNumber, Classes, ClassNumber);
            System.Console.WriteLine("Press any key to continue...");
            System.Console.ReadKey();
        }

        // use the euclidean distane to calculate two coordinates.
        // 勾股定理計算距離
        static double Distance(int x1, int y1, int x2, int y2)
        {
            return Math.Sqrt(Math.Pow((x1 - x2), 2) + Math.Pow((y1 - y2), 2));
        }

        // procedure that show the group
        //顯示每組產生的過程
        static void ShowResult(int[,] Nodes, int NodeNumber, int[,] Classes, int ClassNumber)
        {
            for (int i = 0; i < ClassNumber; i++)
            {
                System.Console.WriteLine("class[{0}]--({1},{2})", i, Classes[i, 0], Classes[i, 1]);
            }
            System.Console.WriteLine("-------------------");
            for (int i = 0; i < NodeNumber; i++)
            {
                System.Console.WriteLine("({0},{1}) --> class[{2}]", Nodes[i, 0], Nodes[i, 1], Nodes[i, 2]);
            }
        }

        // K-means Algorithm
        //Kmeans計算
        static void Kmean(int NodeNumber, int ClassNumber, int[,] Nodes, int[,] Classes)
        {
            // calculate the distance between the class and the coordinate .
            for (int i = 0; i < NodeNumber; i++)
            {
                double min = 100000;
                for (int j = 0; j < ClassNumber; j++)
                {
                    double mindDistance = Distance(Nodes[i, 0], Nodes[i, 1], Classes[j, 0], Classes[j, 1]);
                    if (mindDistance < min)
                    {
                        min = mindDistance;
                        Nodes[i, 2] = j; // flag to set the group that the coordinate belong to.
                    }
                }
            }

           // ShowResult(Nodes, NodeNumber, Classes, ClassNumber);

            // calculate the new center class
            //

            int[,] TempClasses = new int[ClassNumber, 3];
            for (int j = 0; j < ClassNumber; j++)
            {
                int[] TempCoordinate = new int[2];
                for (int i = 0; i < NodeNumber; i++)
                {
                    if (Nodes[i, 2] == j)
                    {
                        // new class
                        TempCoordinate[0] += Nodes[i, 0];
                        TempCoordinate[1] += Nodes[i, 1];
                        TempClasses[j, 2]++;
                    }
                }
                if (TempClasses[j, 2] == 0)TempClasses[j, 2] = 1; //除法分母不為0
                TempClasses[j, 0] = TempCoordinate[0] / TempClasses[j, 2];
                TempClasses[j, 1] = TempCoordinate[1] / TempClasses[j, 2];
                System.Console.WriteLine("count = {3},class[{0}] :new cor ({1},{2})", j, TempClasses[j, 0], TempClasses[j, 1], TempClasses[j, 2]);
            }
            Console.WriteLine();
            int k = 0;
            for (k = 0; k < ClassNumber; k++)
            {
                if ((TempClasses[k, 0] != Classes[k, 0]) || (TempClasses[k, 1] != Classes[k, 1]))
                {
                    RecursiveFlag = true;
                    break;
                }
            }
            if (k == ClassNumber) RecursiveFlag = false;
            if (RecursiveFlag == true)   //New classes center point
            {
                for (int j = 0; j < ClassNumber; j++)
                {
                    Classes[j, 0] = TempClasses[j, 0];
                    Classes[j, 1] = TempClasses[j, 1];
                }
            //    System.Console.ReadKey();
                // recursive
                Kmean(NodeNumber, ClassNumber, Nodes, Classes);
                LoopCount++;
            }
            if (RecursiveFlag == false)
            {
      //          ShowResult(Nodes, NodeNumber, Classes, ClassNumber);
            }
        }
    }


    // procedure for check the same coordinates

}

2017年5月27日 星期六

* Big Two(大老二)

using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace bigtow
{
    class Program
    {
        static void Main(string[] args)
        {
            Player[] players = { new Player("王小明"), new Player("朱胖胖"), new Player("細竣人"), new Player("廖理機") };
           // Player[] players1 = new Player() {"4141","4545"};// { "林華明", "朱晏菱", "張竣凱", "資管提款機" };           
            Deck deck = new Deck();
             //發牌
            deck.Deal(players, deck); 
            //顯示牌
            //deck.ShowCards(players); 
            //出牌
            DealInTurn(players, deck);
            Console.ReadLine();
        }
        /** 出牌 */
        public static void DealInTurn(Player[] players, Deck deck)
        {
            //梅花三在哪個玩家手上
            int PlayerNumber = deck.StartPlayerNum;
            while (players[PlayerNumber].PlayerCards.Count != 0)
            {
                Console.WriteLine(players[PlayerNumber].PlayerName);
                foreach (int item in players[PlayerNumber].PlayerCards)
                {
                    Console.Write(item.ToString() + Card.CardSpecies[item] + " ");
                }
                Console.Write("\n" + players[PlayerNumber].PlayerName + ": ");
                if (players[PlayerNumber].CalculatePlayerCards(deck))
                {
                    PlayerNumber++;
                    Console.WriteLine("-----------------------------------------");
                }
                if (PlayerNumber == 4) PlayerNumber = 0;
                Console.WriteLine();
            }
            Console.WriteLine(players[PlayerNumber].PlayerName + "獲勝");
        }
    }
}

 -------------------------------------------------------------------------------------------------------------------------

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace bigtow
{
    class Card
    {
        
        public static List<Tuple<string>> CardSpecies = new List<Tuple<string>>(); 
        /** rankName: "A", "2", "3"..."J", "Q", "K"
         * suitName:花色*/         
        public String rankName, suitName;
        /** Name of ranks. A,2,3...J,Q,K */

        public Card(int rankNum, int suitNum)
        {
            this.suitName = suitsName[suitNum];
            this.rankName = ranksName[rankNum];
            //每一張排序號與花色
            CardSpecies.Add(Tuple.Create(this.suitName + this.rankName));
        }
        private static String[] ranksName = { "3", "4", "5", "6", "7", "8", "9", "10", "J", "Q", "K", "A", "2" }; 
        /** Name of suits */
        private static String[] suitsName = { "梅花", "方塊", "紅心", "黑桃" }; 
        /** 卡片代號,例如  numOf52CardsByXY[0][0]=0,意思是 [A][梅花]=0 ,  numOf52CardsByXY[12][3]=51 意思是 [k][黑桃]=51 */
        public static int[,] numOf52CardsByXY = new int[13, 4]
        {
            { 0, 1, 2, 3},
            { 4, 5, 6, 7},
            { 8, 9,10,11},
            {12,13,14,15},
            {16,17,18,19},
            {20,21,22,23},
            {24,25,26,27},
            {28,29,30,31},
            {32,33,34,35},
            {36,37,38,39},
            {40,41,42,43},
            {44,45,46,47},
            {48,49,50,51}
        };
        public static Boolean OutCardsNumber(int amount, int[] check, List<int> cards)
        {
            switch (amount)
            {
                case 1:
                    if (cards.Contains(check[0])) return true;
                    else return false;
                case 2:
                    if (cards.Contains(check[0]) && cards.Contains(check[1]))
                        return true;
                    else return false;
                case 5:
                    if (cards.Contains(check[0]) &&
                        cards.Contains(check[1]) &&
                        cards.Contains(check[2]) &&
                        cards.Contains(check[3]) &&
                        cards.Contains(check[4]) )
                        return true;
                    else return false;
                default:
                    break;
            }
            return true;
        }
        public static void OutCardsNumber(string species, int[] delete, List<int> cards)
        {
            switch (species)
            {
                case "單隻":
                    cards.Remove(delete[0]);
                    return;
                case "對子":
                    cards.Remove(delete[0]);
                    cards.Remove(delete[1]);
                    return;
                case "FullHouse":
                    cards.Remove(delete[0]);
                    cards.Remove(delete[1]);
                    cards.Remove(delete[2]);
                    cards.Remove(delete[3]);
                    cards.Remove(delete[4]);
                    return;
                default:
                    return;
            }
        }
    }
}

 ------------------------------------------------------------------------------------------------------------------------- 

using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace bigtow
{
    class Deck
    {
         /** 所有卡片。52個實例化的 Card 陣列 */
        public static List<int> ArrayCardsSuitNum = new List<int>();
        public static List<int> ArrayCardsRankNum = new List<int>();
        public static List<string> TatalCards = new List<string>();
        /** 洗過的牌。值是卡片代號 */
        public List<int> ShuffledCardsNum;    
        /** 已發的牌。第1維索引是卡片代號。第2維索引=0,值是01;索引=1是玩家代號,預設=null */
        public static int[,] CardsDealedByPlayer = new int[52, 2];    
        /** 開始發牌的玩家。此玩家應有梅花3 */
        public int StartPlayerNum;

    
        public Deck()
        {
            CreateAllCards();
            CreateShuffledDeckOfCards();
        }    
        /** 產生allCards */
        public void CreateAllCards()
        {
            int n = 0;
            for (int i = 0; i < 13; i++)
            {
                for (int j = 0; j < 4; j++)
                {
                    Card c = new Card(i, j);
                    TatalCards.Add(Card.CardSpecies[n].ToString());
                    ArrayCardsSuitNum.Add(n);
                    ArrayCardsRankNum.Add(n);
                    n++;
                }
            }
        }
             /** 洗牌 */
        public void CreateShuffledDeckOfCards()
        {
            this.ShuffledCardsNum = new List<int>();
            for (int i = 0; i < 52; i++)
                this.ShuffledCardsNum.Add(i);
            //亂數洗牌 https://msdn.microsoft.com/zh-tw/library/system.collections.arraylist.item(v=vs.110).aspx
            int length = this.ShuffledCardsNum.Count;
            int temp;
            int swapIndex;
            Random rand = new Random();
            for (int i = 0; i < length; i++)
            {
                swapIndex = rand.Next(0, length);
                temp = this.ShuffledCardsNum[i];
                this.ShuffledCardsNum[i] = this.ShuffledCardsNum[swapIndex];
                this.ShuffledCardsNum[swapIndex] = temp;
            }
        }    
        // 發牌
        public void Deal(Player[] players, Deck deck)
        {
            //清除上一次遊戲
            for (int i = 0; i < players.Length; i++)
                players[i].PlayerCards = new List<int>(); //卡片代號

            int CurPlayNum = 0;
           
            for (int i = 0; i < 52; i++)
            {
                int cardNum = deck.ShuffledCardsNum[i];
                players[CurPlayNum].PlayerCards.Add(cardNum);
                if (cardNum == 0)
                { //榪花3的代號=0
                    Console.WriteLine("玩家" + CurPlayNum + " " + players[CurPlayNum].PlayerName.ToString() + " 有梅花3" );
                    deck.StartPlayerNum = CurPlayNum;
                }

                CurPlayNum++;
                if (CurPlayNum == players.Length)
                    CurPlayNum = 0;
            }

            //整理手牌
            for (int i = 0; i < players.Length; i++)
            {
                players[i].PlayerCards.Sort();
            }
        }
        public void ShowCards(Player[] players)
        {
            int n = 0;
            for (int i = 0; i < 4; i++)
            {
                Console.WriteLine(players[i].PlayerName.ToString());
                for (int j = 0; j < 13; j++)
                {
                   // Console.Write(Card.CardSpecies[n].ToString() + "   ");
                    int CardsNum = players[i].PlayerCards[j];
                    Console.Write(CardsNum + "." + Card.CardSpecies[CardsNum] + "  ");
                    n++;
                }
                Console.WriteLine("\n\n");
            }
        }
    }
}

 ------------------------------------------------------------------------------------------------------------------------- 
  
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Collections;

namespace bigtow
{
    class Player
    {
        public String PlayerName;
        public List<int> PlayerCards = new List<int>(); //卡片代號
        static string[] CollectionCards;
        static int[] Cards = new int[5];
        bool debug;
        public Player(string PlayerName)
        {
            this.PlayerName = PlayerName;
        } 
        public Boolean CalculatePlayerCards(Deck deck)
        {           
            //清空
            for (int i = 0; i < 5; i++) Cards[i] = -10;
            string OutCard = Console.ReadLine();
            if (OutCard == "") return true;
            CollectionCards = OutCard.Split(' ');
            try
            {
                int CardNumber = 0;               
                foreach (string card in CollectionCards)
                {
                    Console.Write(Card.CardSpecies[Convert.ToInt32(card)].ToString() + " ");
                    Cards[CardNumber] = Convert.ToInt32(card);
                    CardNumber++;
                }
                //判斷
                if (Card.OutCardsNumber(CardNumber, Cards, PlayerCards))
                    return Collection(CardNumber, OutCard);
                else
                {
                    Console.WriteLine("請確認手排");
                    return false;
                }
            }
            catch (Exception)
            {
                Console.WriteLine("錯誤");
                return false;
            }
        }
        private Boolean Collection(int CardNumber, string OutCard)
        {
            switch (CardNumber)
            {
                case 1:
                    Console.WriteLine("單隻\n");
                    Cards[0] = Convert.ToInt32(OutCard);
                    Card.OutCardsNumber("單隻", Cards, PlayerCards);
                    return true;
                case 2:
                    debug = GetPair();
                    if (!debug) Console.WriteLine("錯誤");
                    return debug;
                case 5:
                    debug = Combination();
                    if (debug) Card.OutCardsNumber("FullHouse", Cards, PlayerCards);
                    else Console.WriteLine("錯誤");
                    return debug;
                default:
                    return false;
            }
        }
        private Boolean GetPair()
        {
            int n = 0;
            int judgment;
            for (int i = 0; i < 13; i++)
            {
                judgment = 0;
                for (int j = 0; j < 4; j++)
                {
                    if (Card.numOf52CardsByXY[i, j] == Cards[0] ||
                        Card.numOf52CardsByXY[i, j] == Cards[1])
                        judgment++;
                    if (judgment == 2)
                    {
                        Console.WriteLine("對子\n");
                        Card.OutCardsNumber("對子", Cards, PlayerCards);
                        return true;
                    }
                }
            }
            return false;
        }
        private Boolean Combination()
        {
            int n = 0;
            int judgment;
            bool pair = false;
            bool triple = false;
            int straight = 0;
            for (int i = 0; i < 13; i++)
            {
                judgment = 0;
                for (int j = 0; j < 4; j++)
                {
                    if (Card.numOf52CardsByXY[i, j] == Cards[0] ||
                        Card.numOf52CardsByXY[i, j] == Cards[1] ||
                        Card.numOf52CardsByXY[i, j] == Cards[2] ||
                        Card.numOf52CardsByXY[i, j] == Cards[3] ||
                        Card.numOf52CardsByXY[i, j] == Cards[4])
                        judgment++;
                }
                if (judgment == 1)
                {
                    straight++;
                    if (straight == 5)
                    {
                        Console.WriteLine("順子\n");
                        return true;
                    }
                }                   
                else straight = 0;
                switch (judgment)
                {
                    case 2:
                        pair = true;
                        break;
                    case 3:
                        triple = true;
                        break;
                    case 4:
                        Console.WriteLine("鐵隻\n");
                        return true;
                    default:
                        break;
                }
            }
            if (pair == true && triple == true)
            {
                Console.WriteLine("葫蘆\n");
                return true;
            }
            Console.WriteLine("錯誤");
            return false;
        }
       
    }
}



WinFormTb02

https://drive.google.com/drive/u/0/folders/1UwS9FZ3ELCOK6SAwirHrkxq3z_RSbxJt https://www.youtube.com/watch?v=k7IkIeww_U0&list=PLumjEWemD...