Advertisement
vencinachev

GrayCode-Recursion

Mar 21st, 2022
733
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.07 KB | None | 0 0
  1. using System;
  2. using System.Collections.Generic;
  3.                    
  4. public class Program
  5. {
  6.     /*
  7.     public static int[] GrayCode(int k)
  8.     {
  9.         int[] result = {1};
  10.         for(int n = 1; n < k; n++)
  11.         {
  12.             int[] newres = new int[2*result.Length + 1];
  13.             int i = 0;
  14.             for(i = 0; i < result.Length; i++)
  15.                 newres[i] = result[i];
  16.             newres[i] = n+1; i++;
  17.             for(int j = i; j <= 2*result.Length; j++)
  18.                 newres[j] = result[j-i];
  19.             result = newres;
  20.         }
  21.         return result;
  22.     }
  23.     */
  24.    
  25.     public static int[] GrayCode(int k){
  26.         List<int> list = new List<int>();
  27.         GrayCode(0, k, list);
  28.         return list.ToArray();
  29.     }
  30.    
  31.    
  32.     public static void GrayCode(int n, int k, List<int> list){
  33.         if (k == n){
  34.             return;
  35.         }
  36.         GrayCode(n, k - 1, list);
  37.         list.Add(k);
  38.         GrayCode(n, k - 1, list);
  39.     }
  40.    
  41.     public static void Main()
  42.     {
  43.         Console.WriteLine(string.Join("", GrayCode(5)));
  44.         /*
  45.         for (int i = 1; i < 7; i++){
  46.            //Console.WriteLine(string.Join("", GrayCode(i)));
  47.         }
  48.         */
  49.     }
  50. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement