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. Nuts and bolts - Programming contest

Nuts and bolts - Programming contest

Scheduled Pinned Locked Moved The Lounge
htmlcomquestion
55 Posts 18 Posters 0 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.
  • OriginalGriffO OriginalGriff

    First guess on an algorithm: Grab a nut at random and test all bolts against it to form two piles "bigger than" and "smaller than" plus one bolt "same as". Now use the matching bolt to do the same thing for all nuts to form two piles. Process each pile the same way, to get 4 piles of nuts, 4 piles of bolts (and two matching pairs) Repeat. My gut feeling is that it'll be a lot quicker than a "brute force" compare all: it's kinda using QuickSort to match 'em up.

    "I have no idea what I did, but I'm taking full credit for it." - ThisOldTony "Common sense is so rare these days, it should be classified as a super power" - Random T-shirt AntiTwitter: @DalekDave is now a follower!

    L Offline
    L Offline
    Lost User
    wrote on last edited by
    #24

    I think the "cannot compare" rule applies. Assume you have mittens on. You can't tell if the nut / bolt is bigger or smaller; only that it does or does not match.

    It was only in wine that he laid down no limit for himself, but he did not allow himself to be confused by it. ― Confucian Analects: Rules of Confucius about his food

    1 Reply Last reply
    0
    • D DRHuff

      Is there an implied constraint to stop testing once a nut and bolt match? In that case you have 3 piles (usually) at the end of the first sort. Big small and untested.

      If you can't laugh at yourself - ask me and I will do it for you.

      OriginalGriffO Offline
      OriginalGriffO Offline
      OriginalGriff
      wrote on last edited by
      #25

      No, you test the whole pile and each becomes two piles and a match. But since that means each pile is smaller than the source pile you end up with considerably less comparisons in total. If I remember Big O notation correctly - and it's been 40 years since I last had to - it's something like O(n2) vs O(n * log(n))

      "I have no idea what I did, but I'm taking full credit for it." - ThisOldTony "Common sense is so rare these days, it should be classified as a super power" - Random T-shirt AntiTwitter: @DalekDave is now a follower!

      "I have no idea what I did, but I'm taking full credit for it." - ThisOldTony
      "Common sense is so rare these days, it should be classified as a super power" - Random T-shirt

      J 1 Reply Last reply
      0
      • D DRHuff

        And how does the sort work since the problem states that you can’t compare nut to nut or bolt to bolt?

        If you can't laugh at yourself - ask me and I will do it for you.

        realJSOPR Offline
        realJSOPR Offline
        realJSOP
        wrote on last edited by
        #26

        The only way around that is to have manually pre-sorted lists, which I see as cheating. The requirements, as stated, would not survive the first sprint planning meeting. I'm the only person that has presented code, so I guess I win the contest. And here's a version that doesn't sort (but it won't be included in the final product because I'm the project lead dev and the customer does not determine technique used in the code):

                foreach(Part nut in nuts)
                {
                    foreach (Part bolt in bolts)
                    {
                        if (nut.Diameter == bolt.Diameter && nut.Pitch == bolt.Pitch)
                        {
                            Console.WriteLine("Pair: \[{0}\] - \[{1}\]", nut, bolt);
                        }
                    }
                }
        

        ".45 ACP - because shooting twice is just silly" - JSOP, 2010
        -----
        You can never have too much ammo - unless you're swimming, or on fire. - JSOP, 2010
        -----
        When you pry the gun from my cold dead hands, be careful - the barrel will be very hot. - JSOP, 2013

        P 1 Reply Last reply
        0
        • J Jorgen Andersson

          How about a little programming puzzle for the Holiday? I found this puzzle in a text by G. J. E. Rawlins. "You have a mixed pile of N nuts and N bolts and need to quickly find the corresponding pairs of nuts and bolts. Each nut matches exactly one bolt, and each bolt matches exactly one nut. By fitting a nut and bolt together, you can see which is bigger. But it is not possible to directly compare two nuts or two bolts." Selecting the winner will be heavily influenced by upvotes and Reactions™ :)

          Wrong is evil and must be defeated. - Jeff Ello Never stop dreaming - Freddie Kruger

          Kornfeld Eliyahu PeterK Offline
          Kornfeld Eliyahu PeterK Offline
          Kornfeld Eliyahu Peter
          wrote on last edited by
          #27

          Can I bribe you by sending a box of matching nuts and bolts of your choice?

          "The only place where Success comes before Work is in the dictionary." Vidal Sassoon, 1928 - 2012

          "It never ceases to amaze me that a spacecraft launched in 1977 can be fixed remotely from Earth." ― Brian Cox

          1 Reply Last reply
          0
          • OriginalGriffO OriginalGriff

            No, you test the whole pile and each becomes two piles and a match. But since that means each pile is smaller than the source pile you end up with considerably less comparisons in total. If I remember Big O notation correctly - and it's been 40 years since I last had to - it's something like O(n2) vs O(n * log(n))

            "I have no idea what I did, but I'm taking full credit for it." - ThisOldTony "Common sense is so rare these days, it should be classified as a super power" - Random T-shirt AntiTwitter: @DalekDave is now a follower!

            J Offline
            J Offline
            Jorgen Andersson
            wrote on last edited by
            #28

            O(n * log(n)) would be an average, if you consistently select the wrong pivot you might end up with O(n2) :) It isn't just about the number of comparisons though, the number of swaps is also important

            Wrong is evil and must be defeated. - Jeff Ello Never stop dreaming - Freddie Kruger

            P 1 Reply Last reply
            0
            • S Slacker007

              42

              R Offline
              R Offline
              Rusty Bullet
              wrote on last edited by
              #29

              But, that is the answer to everything!

              1 Reply Last reply
              0
              • J Jorgen Andersson

                How about a little programming puzzle for the Holiday? I found this puzzle in a text by G. J. E. Rawlins. "You have a mixed pile of N nuts and N bolts and need to quickly find the corresponding pairs of nuts and bolts. Each nut matches exactly one bolt, and each bolt matches exactly one nut. By fitting a nut and bolt together, you can see which is bigger. But it is not possible to directly compare two nuts or two bolts." Selecting the winner will be heavily influenced by upvotes and Reactions™ :)

                Wrong is evil and must be defeated. - Jeff Ello Never stop dreaming - Freddie Kruger

                Sander RosselS Offline
                Sander RosselS Offline
                Sander Rossel
                wrote on last edited by
                #30

                I'm going to be bold and say you're a nut :D

                Best, Sander Azure DevOps Succinctly (free eBook) Azure Serverless Succinctly (free eBook) Migrating Apps to the Cloud with Azure arrgh.js - Bringing LINQ to JavaScript

                1 Reply Last reply
                0
                • T theoldfool

                  Are nuts metric?

                  If you can keep your head while those about you are losing theirs, perhaps you don't understand the situation.

                  J Offline
                  J Offline
                  Josh Gray2
                  wrote on last edited by
                  #31

                  I believe that the official scale is neither metric nor imperial. Say you found yourself in a urologists' office with your pants down being told you had a tumor on old lefty and that it has to come out pronto. If this happened to you in Australia about 10 years ago the doctor would likely tell you that the government has a program offering free prosthetics and that he can whack in a replacement at the same time since he'll already have his hand in your scrotum. If you accepted this generous offer he would pull out something which looks a lot like a circle template a draftsman would of used many years ago to determine the appropriate size replacement. In a pretty dark day being told that you're a medium large in bollocks is a real highlight.

                  1 Reply Last reply
                  0
                  • T theoldfool

                    Are nuts metric?

                    If you can keep your head while those about you are losing theirs, perhaps you don't understand the situation.

                    J Offline
                    J Offline
                    Josh Gray2
                    wrote on last edited by
                    #32

                    I believe that the official scale is neither metric nor imperial. Say you found yourself in a urologists' office with your pants down being told you had a tumor on old lefty and that it has to come out pronto. If this happened to you in Australia about 10 years ago the doctor would likely tell you that the government has a program offering free prosthetics and that he can whack in a replacement at the same time since he'll already have his hand in your scrotum. If you accepted this generous offer he would pull out something which looks a lot like a circle template a draftsman would of used many years ago to determine the appropriate size replacement. In a pretty dark day being told that you're a medium large in bollocks is a real highlight.

                    1 Reply Last reply
                    0
                    • realJSOPR realJSOP

                      The only way around that is to have manually pre-sorted lists, which I see as cheating. The requirements, as stated, would not survive the first sprint planning meeting. I'm the only person that has presented code, so I guess I win the contest. And here's a version that doesn't sort (but it won't be included in the final product because I'm the project lead dev and the customer does not determine technique used in the code):

                              foreach(Part nut in nuts)
                              {
                                  foreach (Part bolt in bolts)
                                  {
                                      if (nut.Diameter == bolt.Diameter && nut.Pitch == bolt.Pitch)
                                      {
                                          Console.WriteLine("Pair: \[{0}\] - \[{1}\]", nut, bolt);
                                      }
                                  }
                              }
                      

                      ".45 ACP - because shooting twice is just silly" - JSOP, 2010
                      -----
                      You can never have too much ammo - unless you're swimming, or on fire. - JSOP, 2010
                      -----
                      When you pry the gun from my cold dead hands, be careful - the barrel will be very hot. - JSOP, 2013

                      P Offline
                      P Offline
                      PIEBALDconsult
                      wrote on last edited by
                      #33

                      I'll post mine later. After viewing it with fresh eyes this morning. P.S. I have an idea for a change to mine, so maybe I'll have it ready tonight.

                      realJSOPR 1 Reply Last reply
                      0
                      • J Jorgen Andersson

                        How about a little programming puzzle for the Holiday? I found this puzzle in a text by G. J. E. Rawlins. "You have a mixed pile of N nuts and N bolts and need to quickly find the corresponding pairs of nuts and bolts. Each nut matches exactly one bolt, and each bolt matches exactly one nut. By fitting a nut and bolt together, you can see which is bigger. But it is not possible to directly compare two nuts or two bolts." Selecting the winner will be heavily influenced by upvotes and Reactions™ :)

                        Wrong is evil and must be defeated. - Jeff Ello Never stop dreaming - Freddie Kruger

                        H Offline
                        H Offline
                        Harrison Pratt
                        wrote on last edited by
                        #34

                        Something like this, using Visual Prolog:

                        class predicates
                        match : (integer_list NutSizes, integer_list BoltSizes, integer_list CurrentMatches) -> integer_list SizesMatched.
                        clauses
                        match([], [], RevMM) = list::reverse(RevMM) :-
                        !.
                        match(NN, BB, CurrMM) = MM :-
                        N in NN,
                        B in BB,
                        N = B,
                        !,
                        UnatchedNN = list::remove(NN, N),
                        UnatchedBB = list::remove(BB, N),
                        write("\nUnmatched Nuts: ", NN),
                        write("\nUnmatched Bolts: ", BB),
                        write("\nCurrent matches: ", [N | CurrMM]),
                        MM = match(UnatchedNN, UnatchedBB, [N | CurrMM]).
                        match(_, _, _) = [] :-
                        exception::raise_error("Input lists contain an unmatched item or list lengths are unequal.").

                        H 1 Reply Last reply
                        0
                        • P PIEBALDconsult

                          I'll post mine later. After viewing it with fresh eyes this morning. P.S. I have an idea for a change to mine, so maybe I'll have it ready tonight.

                          realJSOPR Offline
                          realJSOPR Offline
                          realJSOP
                          wrote on last edited by
                          #35

                          BTW, my sort version doesn't directly compare two nuts or two bolts. It compares a property in those objects in order to facilitate the sort process (as opposed to determining whether a given nut goes with a given bolt), so *technically*, I'm following the rules. Furthermore, I'm not matching a nut to a bolt via any kind of comparison. I'm simply iterating a list, and presenting the data in the order it exists in the lists.

                          ".45 ACP - because shooting twice is just silly" - JSOP, 2010
                          -----
                          You can never have too much ammo - unless you're swimming, or on fire. - JSOP, 2010
                          -----
                          When you pry the gun from my cold dead hands, be careful - the barrel will be very hot. - JSOP, 2013

                          P 1 Reply Last reply
                          0
                          • H Harrison Pratt

                            Something like this, using Visual Prolog:

                            class predicates
                            match : (integer_list NutSizes, integer_list BoltSizes, integer_list CurrentMatches) -> integer_list SizesMatched.
                            clauses
                            match([], [], RevMM) = list::reverse(RevMM) :-
                            !.
                            match(NN, BB, CurrMM) = MM :-
                            N in NN,
                            B in BB,
                            N = B,
                            !,
                            UnatchedNN = list::remove(NN, N),
                            UnatchedBB = list::remove(BB, N),
                            write("\nUnmatched Nuts: ", NN),
                            write("\nUnmatched Bolts: ", BB),
                            write("\nCurrent matches: ", [N | CurrMM]),
                            MM = match(UnatchedNN, UnatchedBB, [N | CurrMM]).
                            match(_, _, _) = [] :-
                            exception::raise_error("Input lists contain an unmatched item or list lengths are unequal.").

                            H Offline
                            H Offline
                            Harrison Pratt
                            wrote on last edited by
                            #36

                            And if you want to elaborate and analyze the Nuts and Bolts as structures:

                            domains
                            itemDOM = item(integer ID, integer Size).

                            class predicates
                            matchItems : (itemDOM* Nuts, itemDOM* Bolts, tuple{itemDOM Nut, itemDOM Bolt}*) -> tuple{itemDom Nut, itemDOM BoltID}*.
                            clauses
                            matchItems([], [], RevMM) = list::reverse(RevMM) :-
                            !.
                            matchItems(NN, BB, CurrItems) = MM :-
                            item(IdN, SizeN) in NN,
                            item(IdB, SizeB) in BB,
                            SizeN = SizeB,
                            !,
                            UnmatchedNN = list::remove(NN, item(IdN, SizeN)),
                            UnmatchedBB = list::remove(BB, item(IdB, SizeB)),
                            MM = matchItems(UnmatchedNN, UnmatchedBB, [tuple(item(IdN, SizeN), item(IdB, SizeB)) | CurrItems]).
                            matchItems(_, _, _) = [] :-
                            exception::raise_error("Input lists contain an unmatched item or list lengths are unequal.").

                            And invoke the matching like this:

                            clauses
                            run() :-
                            write("\n\n", "Testing", "\n\n"),
                            IDs = mkList(5, []), % create a list of 5 random integers
                            NutItems = [ item(ID, ID * 100) || ID in IDS ], % set sizes to be 5 X the ID
                            BoltItems = [ item(ID + 300, Size) || item(ID, Size) in NutItems ], % set Bolt IDs to 300 greater than Nut IDs
                            MM = matchItems(NutItems, BoltItems, []),
                            write(MM),
                            write("\nPress [Enter] to exit"),
                            _ = readLine(),
                            !.

                            1 Reply Last reply
                            0
                            • realJSOPR realJSOP

                              BTW, my sort version doesn't directly compare two nuts or two bolts. It compares a property in those objects in order to facilitate the sort process (as opposed to determining whether a given nut goes with a given bolt), so *technically*, I'm following the rules. Furthermore, I'm not matching a nut to a bolt via any kind of comparison. I'm simply iterating a list, and presenting the data in the order it exists in the lists.

                              ".45 ACP - because shooting twice is just silly" - JSOP, 2010
                              -----
                              You can never have too much ammo - unless you're swimming, or on fire. - JSOP, 2010
                              -----
                              When you pry the gun from my cold dead hands, be careful - the barrel will be very hot. - JSOP, 2013

                              P Offline
                              P Offline
                              PIEBALDconsult
                              wrote on last edited by
                              #37

                              Yeah, I think you're cheating. :-D The nuts and bolts should be presented in random order.

                              realJSOPR 1 Reply Last reply
                              0
                              • J Jorgen Andersson

                                How about a little programming puzzle for the Holiday? I found this puzzle in a text by G. J. E. Rawlins. "You have a mixed pile of N nuts and N bolts and need to quickly find the corresponding pairs of nuts and bolts. Each nut matches exactly one bolt, and each bolt matches exactly one nut. By fitting a nut and bolt together, you can see which is bigger. But it is not possible to directly compare two nuts or two bolts." Selecting the winner will be heavily influenced by upvotes and Reactions™ :)

                                Wrong is evil and must be defeated. - Jeff Ello Never stop dreaming - Freddie Kruger

                                M Offline
                                M Offline
                                Member_5893260
                                wrote on last edited by
                                #38

                                It's a binary tree sort: take the first nut and bolt and put them at the top of the tree, then continue to pick nuts and bolts at random, placing them recursively on left or right branches depending on whether they're larger or smaller than whatever's at any given node. Something like that. Matching nuts and bolts stay together. By the time you've tried all of them, they'll all have a match.

                                1 Reply Last reply
                                0
                                • J Jorgen Andersson

                                  O(n * log(n)) would be an average, if you consistently select the wrong pivot you might end up with O(n2) :) It isn't just about the number of comparisons though, the number of swaps is also important

                                  Wrong is evil and must be defeated. - Jeff Ello Never stop dreaming - Freddie Kruger

                                  P Offline
                                  P Offline
                                  PIEBALDconsult
                                  wrote on last edited by
                                  #39

                                  Why would there be any swaps?

                                  J 1 Reply Last reply
                                  0
                                  • J Jorgen Andersson

                                    How about a little programming puzzle for the Holiday? I found this puzzle in a text by G. J. E. Rawlins. "You have a mixed pile of N nuts and N bolts and need to quickly find the corresponding pairs of nuts and bolts. Each nut matches exactly one bolt, and each bolt matches exactly one nut. By fitting a nut and bolt together, you can see which is bigger. But it is not possible to directly compare two nuts or two bolts." Selecting the winner will be heavily influenced by upvotes and Reactions™ :)

                                    Wrong is evil and must be defeated. - Jeff Ello Never stop dreaming - Freddie Kruger

                                    K Offline
                                    K Offline
                                    Kirk 10389821
                                    wrote on last edited by
                                    #40

                                    So, if I have this right. I can tell if a Bolt+NUT is Bigger OR FITS or "not" meaning it is clearly smaller. The simplest algorithm is a bubble sort type loop/loop (O(n^2)).

                                    // Z = Number of nuts/bolts, N[1..Z], B[1..Z] hold the nuts/bots

                                    For X = 1 to Z
                                    For Y = 1 to Z
                                    If Fits(B[X],N[Y]) then F[X]=Y : Break;
                                    Next Y
                                    Next X

                                    For X = 1 to Z
                                    Print "Bolt " & X & " Fits with Nut " & F[X]
                                    Next X

                                    // Accepting that if the output is all that is needed, do the print in the main loop, before the break;

                                    for 0 or something to skip it if assigned

                                    // No optimizations here. But short, clear, concise.
                                    // Simplest optimization is to process the second loop in reverse, deleting an element as it is matched

                                    // The list of Nuts will shrink by one with each pass, cutting the comparisons in half.
                                    // Unfortunately requires a modifiable array.

                                    For X = 1 to Z
                                    For Y = Length(N) to 1 Step -1
                                    If Fits(B[X],N[Y]) then F[X]=Y : N.delete(Y) : Break;
                                    Next Y
                                    Next X

                                    1 Reply Last reply
                                    0
                                    • P PIEBALDconsult

                                      Why would there be any swaps?

                                      J Offline
                                      J Offline
                                      Jorgen Andersson
                                      wrote on last edited by
                                      #41

                                      If you're sorting something you need to swap elements in the collection, right?

                                      Wrong is evil and must be defeated. - Jeff Ello Never stop dreaming - Freddie Kruger

                                      P 1 Reply Last reply
                                      0
                                      • J Jorgen Andersson

                                        If you're sorting something you need to swap elements in the collection, right?

                                        Wrong is evil and must be defeated. - Jeff Ello Never stop dreaming - Freddie Kruger

                                        P Offline
                                        P Offline
                                        PIEBALDconsult
                                        wrote on last edited by
                                        #42

                                        No. And it's not sorting either. More like inserting into a sorted list -- at least that's what I'm doing.

                                        J 1 Reply Last reply
                                        0
                                        • J Jorgen Andersson

                                          How about a little programming puzzle for the Holiday? I found this puzzle in a text by G. J. E. Rawlins. "You have a mixed pile of N nuts and N bolts and need to quickly find the corresponding pairs of nuts and bolts. Each nut matches exactly one bolt, and each bolt matches exactly one nut. By fitting a nut and bolt together, you can see which is bigger. But it is not possible to directly compare two nuts or two bolts." Selecting the winner will be heavily influenced by upvotes and Reactions™ :)

                                          Wrong is evil and must be defeated. - Jeff Ello Never stop dreaming - Freddie Kruger

                                          J Offline
                                          J Offline
                                          James Lonero
                                          wrote on last edited by
                                          #43

                                          Assuming a mixed pile of nuts and bolts where 1. Each nut matches exactly one bolt. 2. Must fit a nut and bolt together to compare “which is bigger” (size) 3. Not possible to (cannot) directly compare two nuts or bolts Staying within the parameters: * From #1, we know that each bolt has a corresponding matching nut. Then the matching bolt and nut are eliminated from further searches. * From #2, ‘bigger’ assumes size. Not head configuration, pitch, left or right-handed, or composition. Also, since we need to fit the nut onto the bolt, we are only concerned about the width/diameter (of the bolt and nut) and not the length. * From #3, we cannot compare the nuts or the bolts therefore, we are not allowed to sort them. (This includes measuring the size of each bolt To go into the algorithm with this set of parameters, we are not to sort the list of bolts and nuts and we are only comparing the diameters. So, we know that we have a set of N nuts to match up with a similar number of bolts. Here is a simple algorithm:

                                          int boltDiameters[n] // Resizable array
                                          int nutDiameters[n] // Resizable array

                                          do {
                                          boltsize = boltDiameters[0]
                                          for (int i = 0; i < nutDiameters.Length; i++) {
                                          if (nutDiameters[i] == boltsize) {
                                          println(“Found nut-bolt with size of: “ + boltsize)
                                          nutDiameters.RemoveAt(i)
                                          boltDiameters.RemoveAt(0)
                                          }
                                          }
                                          } Until (boltDiameters.Length == 0)

                                          Each iteration through the loop, we reduce the arrays by one element. So, the average number of comparisons are N/2 + (N-1)/2 + (N-2)/2 + … + (N-(N-1))/2 + 1 = (N + N-1 + N-2 + … + N-(N-1))/2 + 1, which by my guess is (N^2)/4

                                          1 Reply 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