finding numbers not sumsble by others

Programming, for all ages and all languages.
User avatar
Alboin
Member
Member
Posts: 1466
Joined: Thu Jan 04, 2007 3:29 pm
Location: Noricum and Pannonia

Post by Alboin »

GLneo wrote:but what if I want to test 3, 4, 5+ numbers?
I'm not really sure....Getting two digits to work in such a small amount of code was kind of hackish by itself. In fact, I'm not entirely sure how isin works... I'm thinking of two ways at the moment for multiples:
  • Expand the table array. This could get ugly for 7 some numbers...
  • Check by trying different combinations of the numbers and calling isin multiple times. Something like:

    Code: Select all

    isin2(n, a,b,c) {
       isin(n, a+b, c)
       isin(n, a+c, b)
       isin(n, c+b, a)
       ...
       Check for certain condition...
    }
    
    I don't know if this method actually works...
C8H10N4O2 | #446691 | Trust the nodes.
GLneo
Member
Member
Posts: 237
Joined: Wed Dec 20, 2006 7:56 pm

Post by GLneo »

O, there has to be a better way, with loops or something...

my brain hurts...
jnc100
Member
Member
Posts: 775
Joined: Mon Apr 09, 2007 12:10 pm
Location: London, UK
Contact:

Post by jnc100 »

If C#'s your thing:

Code: Select all

        static int[] NotSummable(int[] originals, int limit)
        {
            List<int> l = new List<int>(originals);
            List<int> ret = new List<int>();

            for (int i = 1; i < limit; i++)
            {
                bool found = false;
                foreach (int orig in l)
                {
                    if (l.Contains(i - orig) || l.Contains(i))
                    {
                        l.Add(i);
                        found = true;
                        break;
                    }
                }

                if (!found)
                    ret.Add(i);
            }

            return ret.ToArray();
        }
Regards,
John.
User avatar
Solar
Member
Member
Posts: 7615
Joined: Thu Nov 16, 2006 12:01 pm
Location: Germany
Contact:

Post by Solar »

{ algorithm deleted due to severe thinko }
Every good solution is obvious once you've found it.
GLneo
Member
Member
Posts: 237
Joined: Wed Dec 20, 2006 7:56 pm

Post by GLneo »

simple problem, but hard to do with computers :P
Post Reply