Skip to content
  • Categories
  • Recent
  • Tags
  • Popular
  • World
  • Users
  • Groups
Skins
  • Light
  • Cerulean
  • Cosmo
  • Flatly
  • Journal
  • Litera
  • Lumen
  • Lux
  • Materia
  • Minty
  • Morph
  • Pulse
  • Sandstone
  • Simplex
  • Sketchy
  • Spacelab
  • United
  • Yeti
  • Zephyr
  • Dark
  • Cyborg
  • Darkly
  • Quartz
  • Slate
  • Solar
  • Superhero
  • Vapor

  • Default (No Skin)
  • No Skin
Collapse
Code Project
  1. Home
  2. The Lounge
  3. Friday's Coding Challenge

Friday's Coding Challenge

Scheduled Pinned Locked Moved The Lounge
c++architectureperformancehelplounge
76 Posts 35 Posters 6 Views 1 Watching
  • Oldest to Newest
  • Newest to Oldest
  • Most Votes
Reply
  • Reply as topic
Log in to reply
This topic has been deleted. Only users with topic management privileges can see it.
  • J Jason Hooper

    Yeah exactly. Since I'm the first (i think) to propose it but I don't feel like spending 5 hours creating an interpreter, let's just pretend I'm the winner.

    Jason

    B Offline
    B Offline
    BobJanova
    wrote on last edited by
    #46

    I could easily modify my Rowan interpreter (what I posted my solution in) to implement sort as a single symbol, but it isn't worth it just for something like this :-\ . I don't allow composition of functions by juxtaposition like that though because it's confusing (see J).

    1 Reply Last reply
    0
    • C Chris Maunder

      What's the smallest code you can come up with to find the n smallest numbers in a random sample of m numbers where n < m. Any language, speed is not an issue.

      cheers, Chris Maunder The Code Project | Co-founder Microsoft C++ MVP

      R Offline
      R Offline
      Rajesh R Subramanian
      wrote on last edited by
      #47

      std::list li; //A list, so that it can be sorted in ascending order.
      int i = 0, /*i is increment counter*/ n = 3; //n denotes how many small numbers to print.
      while(i++<5) li.push_back(i*3); //fill the list with dummy data.
      li.sort(); //Small numbers will go to the end in ascending order.
      std::list::iterator it = li.begin();

      **while(n-- && it!=li.end()) std::cout << \*(it++) << std::endl;** //This is the line you're looking for. :)
      

      "Real men drive manual transmission" - Rajesh.

      1 Reply Last reply
      0
      • D Dalek Dave

        As an accountant I would suggest...

        Range("A:A").Select
        ActiveWorkbook.Worksheets("Sheet1").Sort.SortFields.Clear
        ActiveWorkbook.Worksheets("Sheet1").Sort.SortFields.Add Key:=Range("A1"), SortOn:=xlSortOnValues, Order:=xlAscending, DataOption:=xlSortNormal
        With ActiveWorkbook.Worksheets("Sheet1").Sort
            .SetRange Range("A:A")
            .Header = xlNo
            .MatchCase = False
            .Orientation = xlTopToBottom
            .SortMethod = xlPinYin
            .Apply
        End With
        Range("C1").Select
        ActiveCell.FormulaR1C1 = "=RC\[-2\]"
        Range("C2").Select
        ActiveCell.FormulaR1C1 = "=COUNTIF(R\[-1\]C\[-2\]:R\[17\]C\[-2\],R\[-1\]C)"
        Range("C3").Select
        

        That that is accountants all over!

        --------------------------------- I will never again mention that I was the poster of the One Millionth Lounge Post, nor that it was complete drivel. Dalek Dave CCC Link[^] English League Tables - Live

        R Offline
        R Offline
        Roger Wright
        wrote on last edited by
        #48

        X| If we're allowed to cheat by using third party software, I'd 1. Copy and paste to Minitab 2. Click on Graphs/Stem and Leaf The top line of numbers in the displayed graph are the smallest values in the set, ordered ascending. :-D

        Will Rogers never met me.

        1 Reply Last reply
        0
        • B BobJanova

          APL:

          f←{⍺↑⍵⌷⍨⍋⍵}

          call like

          n f (sample vector)

          eg

          f←{⍺↑⍵⌷⍨⍋⍵}
          {f}
          xx←20?30 // 20 different ints in 1-30
          (23 28 14 12 10 8 15 3 2 7 26 4 20 29 24 30 25 18 21 27)
          10 f xx // smallest 10 values in xx
          (2 3 4 7 8 10 12 14 15 18)

          This is in my personal dialect since I don't have a licensed major APL on this machine, but the function is essentially the same in normal variants.

          G Offline
          G Offline
          Gary Wheeler
          wrote on last edited by
          #49

          You win the "We Can't Judge Your Submission Because It's Incomprehensible" award.

          Software Zen: delete this;

          B 1 Reply Last reply
          0
          • C Chris Maunder

            What's the smallest code you can come up with to find the n smallest numbers in a random sample of m numbers where n < m. Any language, speed is not an issue.

            cheers, Chris Maunder The Code Project | Co-founder Microsoft C++ MVP

            P Offline
            P Offline
            parths
            wrote on last edited by
            #50

            void find_n_in_m(int *mData, int *nData, unsigned int m, unsigned int n)
            {
            unsigned int ctr, ctr2 = 0;
            for(unsigned int i = 0; i < n; i++)
            nData[i] = mData[i];
            m--;
            while (((ctr = m) && (m >= n))
            && ((mData[ctr] >= nData[ctr2]) ?
            ((++ctr2 < n) || (ctr2 = 0) || m--) :
            (((mData[ctr] ^= nData[ctr2]) && (nData[ctr2] ^= mData[ctr]) && (mData[ctr] ^= nData[ctr2]) && (ctr2 = 0)) || 1)
            ));
            }

            - Doesn't give a sorted list - Modifies the input array (nothing mentioned against that in the specification but that can be avoided by adding an input argument for an temp / scratch buffer of the same size as the source buffer) - Tried it on VS2008 Express Ed and with a few basic data so I don't know if it's correct for all inputs. - What it does is fill the destination with the first n elements then goes about trying to see if it can place the elements from n to m into the new array. Thought I'd post it while I'm trying to improve ( :~ ) it.

            "It was when I found out I could make mistakes that I knew I was on to something." -Ornette Coleman "Philosophy is a study that lets us be unhappy more intelligently." -Anon.

            1 Reply Last reply
            0
            • C Chris Maunder

              What's the smallest code you can come up with to find the n smallest numbers in a random sample of m numbers where n < m. Any language, speed is not an issue.

              cheers, Chris Maunder The Code Project | Co-founder Microsoft C++ MVP

              S Offline
              S Offline
              Single Step Debugger
              wrote on last edited by
              #51

              void Test()
              {
              int arr[] = {1, 4, 6, 8, 9};
              int nNumToGet = 3;

              int \*arr2 = ReturnLowerN(arr, sizeof(arr)/sizeof(int), nNumToGet);
              

              }

              int* ReturnLowerN(int *arr, int arrSize, int nNum)
              {
              std::sort(arr, arr + 5, std::greater<int>());

              return(arr + arrSize - nNum);
              

              }

              Of course if you want to use qsort instead, here is an article from someone you may know. :-D Using qsort on arrays of sequential data[^]

              There is only one Vera Farmiga and Salma Hayek is her prophet! Advertise here – minimum three posts per day are guaranteed.

              1 Reply Last reply
              0
              • B BobJanova

                Well, if not, it is obviously possible to invent a language where one symbol does this operation :P. Since "sort and take" seems to be how to do it, it would be easy to conceive of a language where putting two symbols for "take" and "sort" next to each other would create a composite function that did it, making two characters the sensible theoretical minimum.

                D Offline
                D Offline
                Daniel Grunwald
                wrote on last edited by
                #52

                BobJanova wrote:

                Well, if not, it is obviously possible to invent a language where one symbol does this operation

                Why one symbol? If you're inventing a new language, you might as well invent one where the empty program solves this challenge.

                1 Reply Last reply
                0
                • C Chris Maunder

                  The hamsters have asked for an end to the rumours and baseless allegations of alleged behaviour during certain incidents. The hamsters involved are currently taking some time off to spend more time with their families.

                  cheers, Chris Maunder The Code Project | Co-founder Microsoft C++ MVP

                  R Offline
                  R Offline
                  Roger Wright
                  wrote on last edited by
                  #53

                  I wasn't aware that the Betty Ford Clinic has a hamster wing. How very nice. I hope they enjoy the rest. :-D

                  Will Rogers never met me.

                  1 Reply Last reply
                  0
                  • B BobJanova

                    APL:

                    f←{⍺↑⍵⌷⍨⍋⍵}

                    call like

                    n f (sample vector)

                    eg

                    f←{⍺↑⍵⌷⍨⍋⍵}
                    {f}
                    xx←20?30 // 20 different ints in 1-30
                    (23 28 14 12 10 8 15 3 2 7 26 4 20 29 24 30 25 18 21 27)
                    10 f xx // smallest 10 values in xx
                    (2 3 4 7 8 10 12 14 15 18)

                    This is in my personal dialect since I don't have a licensed major APL on this machine, but the function is essentially the same in normal variants.

                    L Offline
                    L Offline
                    Luc Pattyn
                    wrote on last edited by
                    #54

                    I was thinking about APL too. It has been over 30 years I touched it though. :)

                    Luc Pattyn [My Articles] Nil Volentibus Arduum

                    1 Reply Last reply
                    0
                    • C Chris Maunder

                      What's the smallest code you can come up with to find the n smallest numbers in a random sample of m numbers where n < m. Any language, speed is not an issue.

                      cheers, Chris Maunder The Code Project | Co-founder Microsoft C++ MVP

                      Y Offline
                      Y Offline
                      YvesDaoust
                      wrote on last edited by
                      #55

                      My attempt in plain C:

                      for (i= 0; i < m; i++)
                      {
                      int r= 0;
                      for (j= 0; j < m; j++)
                      r+= a[j] < a[i];
                      if (r < n)
                      printf("%d\n", a[i]);
                      }

                      It simply evaluates the rank of every element. Unfortunately, this method cannot meet the specs in case of equal elements. Actually, it reports all elements with rank less than n.

                      1 Reply Last reply
                      0
                      • C Chris Maunder

                        What's the smallest code you can come up with to find the n smallest numbers in a random sample of m numbers where n < m. Any language, speed is not an issue.

                        cheers, Chris Maunder The Code Project | Co-founder Microsoft C++ MVP

                        Y Offline
                        Y Offline
                        YvesDaoust
                        wrote on last edited by
                        #56

                        Slightly modified Straight Selection Sort will do the trick (moves n lowest elements first):

                        for (int i= 0; i < n; i++)
                        {
                        int k = i;
                        for (int j= i; j < m; j++)
                        {
                        if (a[k] > a[j])
                        {
                        k = j;
                        }
                        }

                        int swap= a\[i\]; a\[i\]= a\[k\]; a\[k\]= swap;
                        

                        }

                        IMHO, allowing function calls makes the challenge nonsensical, as the solutions reduces to S(a, m, n), where S is the function that does just that.

                        T 1 Reply Last reply
                        0
                        • C Chris Maunder

                          What's the smallest code you can come up with to find the n smallest numbers in a random sample of m numbers where n < m. Any language, speed is not an issue.

                          cheers, Chris Maunder The Code Project | Co-founder Microsoft C++ MVP

                          Y Offline
                          Y Offline
                          YvesDaoust
                          wrote on last edited by
                          #57

                          If you don't care about time, sort the whole array and parameter n is virtually useless !

                          S(a, m); // Solution in a[0..n-1]

                          where S stands for some sorting algorithm on an array. Slightly shorter in Python, assuming a has length m:

                          S(a) # Solution in a[0..n-1]

                          1 Reply Last reply
                          0
                          • C Chris Maunder

                            What's the smallest code you can come up with to find the n smallest numbers in a random sample of m numbers where n < m. Any language, speed is not an issue.

                            cheers, Chris Maunder The Code Project | Co-founder Microsoft C++ MVP

                            G Offline
                            G Offline
                            George Danila
                            wrote on last edited by
                            #58

                            var nSmallestNumbers = numbers.OrderBy(x => x).Take(n);

                            1 Reply Last reply
                            0
                            • G Gary Wheeler

                              You win the "We Can't Judge Your Submission Because It's Incomprehensible" award.

                              Software Zen: delete this;

                              B Offline
                              B Offline
                              BobJanova
                              wrote on last edited by
                              #59

                              Thanks but it's actually simple and the same as everyone else's:

                              f←{
                              sorted←⍵⌷⍨⍋⍵; // sorts the right argument
                              ⍺↑sorted // first n items (n = left argument)
                              }

                              1 Reply Last reply
                              0
                              • C Chris Maunder

                                What's the smallest code you can come up with to find the n smallest numbers in a random sample of m numbers where n < m. Any language, speed is not an issue.

                                cheers, Chris Maunder The Code Project | Co-founder Microsoft C++ MVP

                                U Offline
                                U Offline
                                User 8615306
                                wrote on last edited by
                                #60

                                maybe in F# (doesn't check if n < X.Length): let nsmallest X n = (Array.sort X).[0..(n-1)]

                                1 Reply Last reply
                                0
                                • C Chris Maunder

                                  What's the smallest code you can come up with to find the n smallest numbers in a random sample of m numbers where n < m. Any language, speed is not an issue.

                                  cheers, Chris Maunder The Code Project | Co-founder Microsoft C++ MVP

                                  S Offline
                                  S Offline
                                  Spectre_001
                                  wrote on last edited by
                                  #61

                                  // Setup
                                  int n = 2;
                                  int[] m = { 3, 5, 7, 1, 8, 4, 2 };
                                  int[] smallest = (int[])Array.CreateInstance(typeof(int), n);

                                  // My answer
                                  Array.Sort(m); Array.ConstrainedCopy(m, 0, smallest, 0, n);

                                  Kevin Rucker, Application Programmer QSS Group, Inc. United States Coast Guard OSC Kevin.D.Rucker@uscg.mil "Programming is an art form that fights back." -- Chad Hower

                                  1 Reply Last reply
                                  0
                                  • C Chris Maunder

                                    What's the smallest code you can come up with to find the n smallest numbers in a random sample of m numbers where n < m. Any language, speed is not an issue.

                                    cheers, Chris Maunder The Code Project | Co-founder Microsoft C++ MVP

                                    E Offline
                                    E Offline
                                    eltashi
                                    wrote on last edited by
                                    #62

                                    Hi there, nice challenge ! Didn't want to use language built in array sorting, since that makes the solution obvious. Ok ok, recursion is dangerous, but looks nice :)

                                    function reduceTo(arr,n){

                                    if (n==arr.length) return arr;
                                    var next=Array();
                                    	
                                    for (i=0,max=0; i\=arr\[max\]) {
                                    		if (max!=i) next\[next.length\]=arr\[max\];
                                    		max=i;
                                    	}
                                    	else{
                                    		next\[next.length\]=arr\[i\];
                                    	}
                                    }
                                    
                                    return reduceTo(next,n);
                                    

                                    }

                                    1 Reply Last reply
                                    0
                                    • C Chris Maunder

                                      What's the smallest code you can come up with to find the n smallest numbers in a random sample of m numbers where n < m. Any language, speed is not an issue.

                                      cheers, Chris Maunder The Code Project | Co-founder Microsoft C++ MVP

                                      F Offline
                                      F Offline
                                      faceless5579
                                      wrote on last edited by
                                      #63

                                      in Java :-) (without dublicates handling) // given an array of ints: m // and a number n, for example n =4 // we can use a java.util.TreeSet (that is, ordered set) to do the job: TreeSet result = new TreeSet (); for (int mcnt=0; mcnt < m.length ; mcnt++) if (result.size() < n) { result.add(m[mcnt]); continue; } else { int curMax = result.last(); if (curMax > m[mcnt]) { result.remove(curMax); result.add(m[mcnt]); } }

                                      1 Reply Last reply
                                      0
                                      • C Chris Maunder

                                        What's the smallest code you can come up with to find the n smallest numbers in a random sample of m numbers where n < m. Any language, speed is not an issue.

                                        cheers, Chris Maunder The Code Project | Co-founder Microsoft C++ MVP

                                        T Offline
                                        T Offline
                                        Trajan McGill
                                        wrote on last edited by
                                        #64

                                        A submission in C:

                                        #include
                                        int*f(int*s,int m,int n){int i,c,*a=(int*)malloc(n*sizeof(int));for(;n;m--,s++){for(i=1,c=0;i
                                        Assumptions: the numbers are integers, "smaller" for negative numbers means "more negative", and the initial set of numbers is stored as an array. A different data structure would require reworking the algorithm, but the first two assumptions are easy to change with a few extra bytes-- for instance, for doubles, we can do it as:

                                        #include
                                        #define D double
                                        D*f(D*s,int m,int n){int i,c;D*a=(D*)malloc(n*sizeof(D));for(;n;m--,s++){for(i=1,c=0;i
                                        and for a "closer to zero" definition of smaller numbers, the integer version would change to:

                                        #include
                                        #include
                                        int*f(int*s,int m,int n){int i,c,*a=(int*)malloc(n*sizeof(int));for(;n;m--,s++){for(i=1,c=0;i
                                        If you test it, don't forget to free() the returned array. And for heaven's sake, don't ever write real code like this (and I don't just mean the formatting).

                                        1 Reply Last reply
                                        0
                                        • Y YvesDaoust

                                          Slightly modified Straight Selection Sort will do the trick (moves n lowest elements first):

                                          for (int i= 0; i < n; i++)
                                          {
                                          int k = i;
                                          for (int j= i; j < m; j++)
                                          {
                                          if (a[k] > a[j])
                                          {
                                          k = j;
                                          }
                                          }

                                          int swap= a\[i\]; a\[i\]= a\[k\]; a\[k\]= swap;
                                          

                                          }

                                          IMHO, allowing function calls makes the challenge nonsensical, as the solutions reduces to S(a, m, n), where S is the function that does just that.

                                          T Offline
                                          T Offline
                                          Trajan McGill
                                          wrote on last edited by
                                          #65

                                          Ahh, shoot, you're right. The requirements didn't specify a non-destructive algorithm. Your method, turned into an actual function, with a few optimizations and a bit of non-essential character elimination, reduces to:

                                          void g(int*a,int m,int n){int i=0,j,k,t;for(;ia[j])k=j;}

                                          which beats mine by 50 characters (49 if I chop out the one removable whitespace character I missed in my solution). If we modify it further to toss out the array notation and instead do horrible things with pointers, we can even save 6 more:

                                          void g(int*a,int m,int n){int*i=a,*j,*k,t;for(;i*j)k=j;}

                                          Y 2 Replies Last reply
                                          0
                                          Reply
                                          • Reply as topic
                                          Log in to reply
                                          • Oldest to Newest
                                          • Newest to Oldest
                                          • Most Votes


                                          • Login

                                          • Don't have an account? Register

                                          • Login or register to search.
                                          • First post
                                            Last post
                                          0
                                          • Categories
                                          • Recent
                                          • Tags
                                          • Popular
                                          • World
                                          • Users
                                          • Groups