Archive for the ‘General’ Category

Project Euler Problem #43!

July 27th, 2009

Problem #43 says:

The number, 1406357289, is a 0 to 9 pandigital number because
 it is made up of each of the digits 0 to 9 in some order, but it also
has a rather interesting sub-string divisibility property.

Let d_(1) be the 1^(st) digit, d_(2) be the 2^(nd) digit, and so on.
In this way, we note the following:

    * d_(2)d_(3)d_(4)=406 is divisible by 2
    * d_(3)d_(4)d_(5)=063 is divisible by 3
    * d_(4)d_(5)d_(6)=635 is divisible by 5
    * d_(5)d_(6)d_(7)=357 is divisible by 7
    * d_(6)d_(7)d_(8)=572 is divisible by 11
    * d_(7)d_(8)d_(9)=728 is divisible by 13
    * d_(8)d_(9)d_(10)=289 is divisible by 17

Find the sum of all 0 to 9 pandigital numbers with this property.

This Problem along with problem #41 were done as battery test for my new computer and use a brute force method to solve the problem with little or no optimization. Therefor they take a long time to run. I will probably return at some point and see if i cannot speed things up. Until then Solution in C#/mono.

using System;
using System.Diagnostics;
using System.Collections;
using System.Collections.Generic;
using System.Text;

namespace ProjectEuler
{
    class Program
    {
        static void Main(string[] args)
        {
            Stopwatch sw = new Stopwatch();
            sw.Start();
            long Answer = 0;

            long Stepper = 1000000000;
            long Max = 9999999999;
            while (Stepper <= Max)
            {
                if (CheckNum(Stepper))
                {
                    Answer += Stepper;
                }
                if (Stepper % 5000000 == 0)
                {
                    Console.WriteLine(Stepper.ToString() +
                          " :: " + (((float)Stepper / (float)Max) * (float)100).ToString());

                }
                Stepper++;
            }

            Console.WriteLine(Answer);
            sw.Stop();
            Console.WriteLine(sw.Elapsed);
            Console.ReadLine();
        }
        static bool CheckNum(long num)
        {
            if (num.ToString().Length != 10)
            {
                return false;
            }
            if (IsPandigital(num) != 1)
            {
                return false;
            }
            string Num = num.ToString();
            int d1 = int.Parse(Num[0].ToString());
            int d2 = int.Parse(Num[1].ToString());
            int d3 = int.Parse(Num[2].ToString());
            int d4 = int.Parse(Num[3].ToString());
            int d5 = int.Parse(Num[4].ToString());
            int d6 = int.Parse(Num[5].ToString());
            int d7 = int.Parse(Num[6].ToString());
            int d8 = int.Parse(Num[7].ToString());
            int d9 = int.Parse(Num[8].ToString());
            int d10 = int.Parse(Num[9].ToString());

            if (((d2 * 100) + (d3 * 10) + d4) % 2 != 0)
            {
                return false;
            }
            if (((d3 * 100) + (d4 * 10) + d5) % 3 != 0)
            {
                return false;
            }
            if (((d4 * 100) + (d5 * 10) + d6) % 5 != 0)
            {
                return false;
            }
            if (((d5 * 100) + (d6 * 10) + d7) % 7 != 0)
            {
                return false;
            }
            if (((d6 * 100) + (d7 * 10) + d8) % 11 != 0)
            {
                return false;
            }
            if (((d7 * 100) + (d8 * 10) + d9) % 13 != 0)
            {
                return false;
            }
            if (((d8 * 100) + (d9 * 10) + d10) % 17 != 0)
            {
                return false;
            }
            return true;
        }
        static long IsPandigital(long i)
        {
            char[] I = i.ToString().ToCharArray();
            long[] counters = new long[9] { 0, 0, 0, 0, 0, 0, 0, 0, 0 };

            foreach (char c in I)
            {
                switch (c)
                {
                    case '1':
                        counters[0] += 1;
                        break;
                    case '2':
                        counters[1] += 1;
                        break;
                    case '3':
                        counters[2] += 1;
                        break;
                    case '4':
                        counters[3] += 1;
                        break;
                    case '5':
                        counters[4] += 1;
                        break;
                    case '6':
                        counters[5] += 1;
                        break;
                    case '7':
                        counters[6] += 1;
                        break;
                    case '8':
                        counters[7] += 1;
                        break;
                    case '9':
                        counters[8] += 1;
                        break;
                }
            }
            foreach (long Check in counters)
            {
                if (Check > 1)
                    return -1;
                if (Check == 0)
                    return 0;
            }

            return 1;
        }

    }
}

Posted in General | Comments (0)

I’m not dead yet.

April 22nd, 2009

Alrighty people. I know that I haven’t updated in a few days. I’ve been busy with school (getting ready for finals) and playing with new python tech’s (python storm for example). So yeah the sites probably not going to be updated all that frequently for a while.

On the other hand, I have several projects in the works (including several project euler solutions). So once things lighten up I’ll probably have a lot of stuff to post.

So in short, I’m not dead, neither is the site, etc, etc.

Next time I post I’ll have something more interesting to say.

Posted in General | Comments (0)

Updated Radix Sort.

April 15th, 2009

It was pointed out to me that my previous Radix sort on my site would lose items from its list to sort so I’m posting it here with that bug fixed and with a huge improvement in performance (2x the performance when sorting 1 million 1-3 digit numbers)

So here it is in C#/Mono.

using System;
using System.Collections;
using System.Collections.Generic;
using System.Text;
namespace RadixSort
{
    class Program
    {
        static void Main(string[] args)
        {
            System.Random rand = new Random(System.DateTime.Now.Millisecond);
            int items = 1000000; //Convert.ToInt32(args[0]);

            Queue Items = new Queue();
            int c = 0;
            while (c <= items)
            {
                Items.Enqueue(rand.Next(0, 999));
                c++;
            }
            System.Diagnostics.Stopwatch sw = new System.Diagnostics.Stopwatch();
            sw.Start();
            Items = RadixSort(Items, 3);
            sw.Stop();
            Console.WriteLine("Sorted in :: " + sw.Elapsed.ToString());
            Console.ReadLine();
        }
        static Queue RadixSort(Queue Items, int Digits)
        {

            int Digit = Digits - 1;
            while (Digit >= 0)
            {
                Queue Zero = new Queue();
                Queue One = new Queue();
                Queue Two = new Queue();
                Queue Three = new Queue();
                Queue Four = new Queue();
                Queue Five = new Queue();
                Queue Six = new Queue();
                Queue Seven = new Queue();
                Queue Eight = new Queue();
                Queue Nine = new Queue();
                int UpperLimit = Items.Count;
                int counter = 1;
                while (counter <= UpperLimit)
                {
                    int i = Convert.ToInt32(Items.Dequeue());
                    counter++;

                    switch (i.ToString().PadLeft(Digits, '0')[Digit])
                    {
                        case '0':
                            Zero.Enqueue(i);
                            continue;
                        case '1':
                            One.Enqueue(i);
                            continue;
                        case '2':
                            Two.Enqueue(i);
                            continue;
                        case '3':
                            Three.Enqueue(i);
                            continue;
                        case '4':
                            Four.Enqueue(i);
                            continue;
                        case '5':
                            Five.Enqueue(i);
                            continue;
                        case '6':
                            Six.Enqueue(i);
                            continue;
                        case '7':
                            Seven.Enqueue(i);
                            continue;
                        case '8':
                            Eight.Enqueue(i);
                            continue;
                        case '9':
                            Nine.Enqueue(i);
                            continue;
                    }
                }
                Items = new Queue();
                foreach (int i in Zero)
                {
                    Items.Enqueue(i);
                }
                foreach (int i in One)
                {
                    Items.Enqueue(i);
                }
                foreach (int i in Two)
                {
                    Items.Enqueue(i);
                }
                foreach (int i in Three)
                {
                    Items.Enqueue(i);
                }
                foreach (int i in Four)
                {
                    Items.Enqueue(i);
                }
                foreach (int i in Five)
                {
                    Items.Enqueue(i);
                }
                foreach (int i in Six)
                {
                    Items.Enqueue(i);
                }
                foreach (int i in Seven)
                {
                    Items.Enqueue(i);
                }
                foreach (int i in Eight)
                {
                    Items.Enqueue(i);
                }
                foreach (int i in Nine)
                {
                    Items.Enqueue(i);
                }
                Digit--;
            }
            return Items;
        }
    }
}

I’ll probably keep updating this periodically as new improvements come to me. That and quite a few people seem to find my site looking for a radix sort on google.

Posted in General | Comments (1)

RealTek Audio, Vista, And my irc bot.

April 12th, 2009

Ok starting from the beginning.

1. RealTek Audio & Vista:

This has been bothering me for a while actually but I finally found a way to fix it. occasionally programs would lose sound. This persisted across restarts and updating drivers hadn’t helped. So what I noticed is that when programs stop working the sound mixer app would have a listing for “unnamed application” that was permanently stuck there. So the thing I’ve found that fixes it is to go to “control panel” then click on “sound” select your active output then click on “Properties” go to the “Advanced” tab then under the “default format” and select anything other than what you have now. click apply and then change it back and click apply again. For me this works 100% of the time. And has fixed issues with games such as crysis and COD5 where they lost there sound.

as for #2. The IRC Bot:

I’ve recently managed to get a test irc server setup on my local network so that I don’t have to make changes on a live system. And found that it doesn’t work right on this system (ubuntu 8.04 and inspircd) it appears that the welcome method isn’t triggered when it connects to the server. so it just sits there without joining any channels (among other things). I’m working to fix this and will post an updated version eventually.

Posted in General | Comments (0)

More python irc goodness.

April 2nd, 2009

In response to the search terms that are bringing people here to find my modified irc bot I’ll give you the following.

if you want to be able to private message the irc bot to kick someone from your channel it’s very easy to add (or if your a network oper this bot does support a server kill and a kline with very little effort).

The following is the only thing you would need to add to the bot to kick people on command. Please note that this does not check to see who sent the command so if people find out the command anybody could kick anybody with a lower privilege than the bot (for instance if the bot is half op ANYBODY that knows this command could kick people with voice or below but not a full chan op or chan founder)

   def kick(m,origin,args,text,bot=bot):
       cmd = text.split() #get the individual words in the command
       bot.kick(cmd[1],cmd[2]) #cmd[1] is the channel cmd[2] is the persons nick
   bot.rule(kick,'kick',r'!kick')

so the bot now looks like.

#!/usr/bin/python
"""
ircbot.py - An IRC Bot Basis in Python

License:
   W3C Open Source License; share and enjoy!

http://www.w3.org/Consortium/Legal/copyright-software-19980720

Original:

http://dev.w3.org/cvsweb/2000/scribe-bot/ircAsync.py

   Dan Connolly and Tim Berners-Lee
   Copyright (c) 2001 W3C (MIT, INRIA, Keio)

Augmentations' Author:
   Sean B. Palmer, inamidst.com

This version updated by: Serinox

"""

import sys, os, re, socket, asyncore, asynchat, re, commands

protect = True
filename = "irc.log"
FILE = open(filename,"a")

proxyacl = "/usr/local/proxy/conf/access.conf"

PACL = open(filename,"a")

class Origin(object):
   def __init__(self, origin):
      self.origin = origin
      self.split(origin)

   def __str__(self):
      return self.origin

   def split(self, origin):
      if origin and '!' in origin:
         self.nick, userHost = origin.split('!', 1)
         if '@' in userHost:
            self.user, self.host = userHost.split('@', 1)
         else: self.user, self.host = userHost, None
      else: self.nick, self.user, self.host = origin, None, None

   def replyTo(self, nickname, args):
      if (not args) or (len(args) < 2): return
      target = args[1]
      if target == nickname:
         self.sender = self.nick
      else: self.sender = target

def ctcp(s): return 'x01%sx01' % s
def me(s): return ctcp('ACTION %s' % s)

class Bot(asynchat.async_chat):
   def __init__(self, nick=None, userid=None, name=None, channels=None):
      asynchat.async_chat.__init__(self)
      self.bufIn = ''
      self.set_terminator('rn')

      self.nick = nick or 'Ted'
      self.userid = userid or 'Ted'
      self.name = name or 'Ted'

      self.documentation = {}
      self.info = {}
      self.dispatch = []
      self.msgstack = []

      self.channels = channels or ['#test']
      self.rule(self.welcome, 'welcome', cmd='001')
      self.rule(self.help, 'help', '%s[:,] help (w+)??' % self.nick)

   def run(self, host, port):
      port = port or 6667
      self.create_socket(socket.AF_INET, socket.SOCK_STREAM)
      debug("connecting to...", host, port)
      self.connect((host, port))
      self.bufIn = ''
      asyncore.loop()

   def welcome(self, m, origin, args, text):
      for chan in self.channels:
         self.todo(['JOIN', chan])
      self.msg("nickserv","identify NICKSERV PASSWORD")
      self.todo(['OPER',"Phil Poper123!"])

   def help(self, m, origin, args, text):
      command = m.group(1)
      if self.documentation.has_key(command):
         doc = self.documentation[command]
         self.msg(origin.sender, '%s: %s' % (command, doc))
      else: self.msg(origin.sender, 'No help available for %s.' % command)

   def todo(self, args, *text):
      command = ' '.join(args)
      if text: command = command + ' :' + ' '.join(text)

      self.push(command + 'rn')
      debug("sent/pushed command:", command)

   def handle_connect(self):
      debug("connected")

      self.todo(['PASS',"IRC SERVER PASSWORD"])
      self.todo(['NICK', self.nick])
      self.todo(['USER', self.userid, "+iw", self.nick], self.name)

   def collect_incoming_data(self, bytes):
      self.bufIn = self.bufIn + bytes
      FILE = open(filename,"a")
      FILE.writelines(self.bufIn+"n")
      FILE.close()
   def found_terminator(self):
      line = self.bufIn
      self.bufIn = ''

      if line.startswith(':'):
         origin, line = line[1:].split(' ', 1)
         origin = Origin(origin)
      else: origin = None

      try: args, text = line.split(' :', 1)
      except ValueError:
         args, text = line, ''
      args = args.split()

      if origin: origin.replyTo(self.nick, args)
      debug("from::", origin, "|message::", args, "|text::", text)
      self.rxdMsg(args, text, origin)

   def rule(self, func, name, regexp=None, doc=None, cmd=None):
      if isinstance(regexp, basestring):
         regexp = re.compile(regexp)
      if self.documentation.has_key(name):
         raise "DispatchError", "Function %s already added" % name
      doc = doc or func.__doc__
      if doc and doc.strip():
         self.documentation[name] = doc
      self.dispatch.append((cmd or 'PRIVMSG', regexp, func))

   def bind(self, func, cmd, regexp):
      self.dispatch.append((cmd, re.compile(regexp), func))

   def rxdMsg(self, args, text, origin):
      if args[0] == 'PING':
         self.todo(['PONG', text])

      for cmd, pat, thunk in self.dispatch:
         if args[0] == cmd:
            if pat:
               m = pat.search(text)
               if not m: continue
            else: m = None

            if protect:
               try: thunk(m, origin, args, text)
               except Exception, e:
                  try: self.msg(origin.sender, "%s: %s" % (e.__class__, e))
                  except: print >> sys.stderr, "%s: %s" % (e.__class__, e)
            else: thunk(m, origin, args, text)

   def pushMsg(self, msg):
      self.msgstack = self.msgstack[-9:]
      self.msgstack.append(msg)

   def msg(self, dest, text):
      # Flood protection
      if self.msgstack.count(text) >= 50:
         text = '...'
      if self.msgstack.count('...') >= 20:
         if text == '...': return

      if len(''.join(self.msgstack[:-3])) > 200:
         import time
         time.sleep(2)

      self.pushMsg(text)
      self.todo(['PRIVMSG', dest], text)

   def kick(self, dest, text):
      self.todo(['KICK', dest], text)

   #def join(self, chan):
   #   self.todo(['JOIN', chan])

   def safeMsg(self, channel, lines):
      import time
      for line in lines:
         if line: self.msg(channel, line)
         time.sleep(1)
         if len(line) > 50: time.sleep(0.7)

   def notice(self, dest, text):
      self.todo(['NOTICE', dest], text)

def debug(*args):
   sys.stderr.write("DEBUG: ")
   for a in args:
      sys.stderr.write(str(a))
   sys.stderr.write("n")
def doubleFork():
   # http://swhack.com/logs/2004-05-12#T10-20-11
   # http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/66012
   try:
      pid = os.fork()
      if pid > 0: sys.exit(0)
   except OSError, e:
      print >> sys.stderr, "fork #1 failed: %d (%s)" % (e.errno, e.strerror)
      sys.exit(1)
   os.chdir("/")
   os.setsid()
   os.umask(0)
   try:
      pid = os.fork()
      if pid > 0:
         print "Daemon PID %d" % pid
         sys.exit(0)
   except OSError, e:
      print >> sys.stderr, "fork #2 failed: %d (%s)" % (e.errno, e.strerror)
      sys.exit(1)

def test(host, port, channels):
   bot = Bot(nick='Ted', channels=channels)

   Troutex = re.compile(".*?(trout)")
   def trout(m, origin, args, text, bot=bot):
      bot.kick(origin.sender, origin.nick)
   bot.rule(trout, 'trout', Troutex)

   def action(m,origin,args,text,bot=bot):
       cmd = text.split()
       chan = cmd[1]
       cmd[0] = ""
       cmd[1] = ""
       cmd.remove("")
       cmd = " ".join(cmd)
       bot.msg(chan,"ACTION "+cmd+"")
   bot.rule(action,'action',r'!action')

   def kick(m,origin,args,text,bot=bot):
       cmd = text.split() #get the individual words in the command
       bot.kick(cmd[1],cmd[2]) #cmd[1] is the channel cmd[2] is the persons nick
   bot.rule(kick,'kick',r'!kick')

   bot.run(host, port)

if __name__=='__main__':
   test('SERVERIP', PORTNUMBER, ['#CHANNEL'])

Telling the bot to kick someone would be done like so.

/msg <BotName> !kick <channel> <targets nick>

I’ve used this in the past to give semi-trustworthy people the ability to kick people from the room without giving them anything above +v in a channel. Alternatively this could be extended to kick people when they say something specific (e.g. trout).

Posted in General | Comments (0)