Guest User

xkcd c#

a guest
Apr 15th, 2018
140
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.12 KB | None | 0 0
  1. using System;
  2. using System.Web;
  3. using System.Net.Http;
  4. using System.Text.RegularExpressions;
  5. using Newtonsoft.Json.Linq;
  6.  
  7. namespace ConsoleApp1 {
  8.     class Program {
  9.         static Regex rXKCDAddress = new Regex(@"https://xkcd\.com/\d+", RegexOptions.Compiled);
  10.         static Random r = new Random();
  11.         static HttpClient c = new HttpClient();
  12.         static int l = JObject.Parse(c.GetStringAsync("https://xkcd.com/info.0.json").Result).GetValue("num").Value<int>();
  13.  
  14.         static void Main() {
  15.             while (true)
  16.                 Console.WriteLine(XKCD(Console.ReadLine()));
  17.         }
  18.  
  19.         static string XKCD(string s) {
  20.             if (int.TryParse(s, out int n) && n <= l)
  21.                 return "https://xkcd.com/" + n;
  22.             if (string.IsNullOrWhiteSpace(s))
  23.                 return "https://xkcd.com/" + r.Next(1, l + 1);
  24.             return rXKCDAddress.Match(c.GetStringAsync("https://www.google.com/search?source=hp&q=site%3Axkcd.com+-site%3Aforums.xkcd.com+-site%3Ablog.xkcd.com+-site%3Afora.xkcd.com+" + HttpUtility.HtmlEncode(s.Replace(' ', '+'))).Result).Value;
  25.         }
  26.     }
  27. }
Advertisement
Add Comment
Please, Sign In to add comment