Ruby: sorting an assortment of strings and integers together, while keeping them separate

Does "variables should live in the smallest scope as possible" include the case "variables should not exist if possible"?

Can a bounded number sequence be strictly ascending?

Accountant/ lawyer will not return my call

Does splitting a potentially monolithic application into several smaller ones help prevent bugs?

Are babies of evil humanoid species inherently evil?

Offered promotion but I'm leaving. Should I tell?

Replacing Windows 7 security updates with anti-virus?

How much attack damage does the AC boost from a shield prevent on average?

Built-In Shelves/Bookcases - IKEA vs Built

Can Mathematica be used to create an Artistic 3D extrusion from a 2D image and wrap a line pattern around it?

How to pass a string to a command that expects a file?

Why is Beresheet doing a only a one-way trip?

Grey hair or white hair

Are the terms "stab" and "staccato" synonyms?

Why is there a voltage between the mains ground and my radiator?

How can I budget to build up a down payment for a house over the course of a year?

Why the color red for the Republican Party

How to create a hard link to an inode (ext4)?

What to do when during a meeting client people start to fight (even physically) with each others?

What Happens when Passenger Refuses to Fly Boeing 737 Max?

Who deserves to be first and second author? PhD student who collected data, research associate who wrote the paper or supervisor?

Reverse string, can I make it faster?

Is there an equal sign with wider gap?

Word for a person who has no opinion about whether god exists



Ruby: sorting an assortment of strings and integers together, while keeping them separate














0












$begingroup$


I put a solution to this coding problem together. The problem is this:




Create a function that takes an array, finds the most often repeated element(s) within it and returns it/them in an array. The function should work for both integers and strings mixed together within the input list (e.g. [1, 1, "a"]).



If there is a tie for highest occurrence, return both.



Separate integers and strings in the result.



If returning multiple elements, sort result alphabetically with numbers coming before strings.




This is the solution I came up with:



def highest_occurrence(arr)

# Separate the unique values into individual sub-arrays
x = rand(2**32).to_s(16)
result = arr.sort do |a, b|
a = a.to_s + x if a.is_a?(Numeric)
b = b.to_s + x if b.is_a?(Numeric)
a <=> b
end.chunk_while {|a, b| a == b }.to_a

# Get an array of all of the individual values with the max size,
# Sort them by integers first, strings second
result = result.select do |a2|
a2.size == result.max_by(&:size).size
end.map(&:uniq).flatten.sort_by { |v| v.class.to_s }

end


It passes these tests:



p highest_occurrence(["a","a","b","b"]) == ["a","b"]
p highest_occurrence([1,"a","b","b"]) == ["b"]
p highest_occurrence([1,2,2,3,3,3,4,4,4,4]) == [4]
p highest_occurrence(["ab","ab","b"]) == ["ab"]
p highest_occurrence(["ab","ab","b","bb","b"]) == ["ab","b"]
p highest_occurrence([3,3,3,4,4,4,4,2,3,6,7,6,7,6,7,6,"a","a","a","a"]) == [3,4,6,"a"]
p highest_occurrence([2,2,"2","2",4,4]) == [2,4,"2"]


I'd like to know whether there are better ways to solve some of the specific problems in this exercise. In particular, the requirement to sort strings and integers together without being able to convert the integers to strings in the sort block was an interesting one. I managed this by appending a random hex value (the same value) to each integer during the sort process. This seems a bit hackish, and I have the feeling it could be improved upon.



I would also appreciate any other suggestions for how to do a cleaner job.









share









$endgroup$

















    0












    $begingroup$


    I put a solution to this coding problem together. The problem is this:




    Create a function that takes an array, finds the most often repeated element(s) within it and returns it/them in an array. The function should work for both integers and strings mixed together within the input list (e.g. [1, 1, "a"]).



    If there is a tie for highest occurrence, return both.



    Separate integers and strings in the result.



    If returning multiple elements, sort result alphabetically with numbers coming before strings.




    This is the solution I came up with:



    def highest_occurrence(arr)

    # Separate the unique values into individual sub-arrays
    x = rand(2**32).to_s(16)
    result = arr.sort do |a, b|
    a = a.to_s + x if a.is_a?(Numeric)
    b = b.to_s + x if b.is_a?(Numeric)
    a <=> b
    end.chunk_while {|a, b| a == b }.to_a

    # Get an array of all of the individual values with the max size,
    # Sort them by integers first, strings second
    result = result.select do |a2|
    a2.size == result.max_by(&:size).size
    end.map(&:uniq).flatten.sort_by { |v| v.class.to_s }

    end


    It passes these tests:



    p highest_occurrence(["a","a","b","b"]) == ["a","b"]
    p highest_occurrence([1,"a","b","b"]) == ["b"]
    p highest_occurrence([1,2,2,3,3,3,4,4,4,4]) == [4]
    p highest_occurrence(["ab","ab","b"]) == ["ab"]
    p highest_occurrence(["ab","ab","b","bb","b"]) == ["ab","b"]
    p highest_occurrence([3,3,3,4,4,4,4,2,3,6,7,6,7,6,7,6,"a","a","a","a"]) == [3,4,6,"a"]
    p highest_occurrence([2,2,"2","2",4,4]) == [2,4,"2"]


    I'd like to know whether there are better ways to solve some of the specific problems in this exercise. In particular, the requirement to sort strings and integers together without being able to convert the integers to strings in the sort block was an interesting one. I managed this by appending a random hex value (the same value) to each integer during the sort process. This seems a bit hackish, and I have the feeling it could be improved upon.



    I would also appreciate any other suggestions for how to do a cleaner job.









    share









    $endgroup$















      0












      0








      0





      $begingroup$


      I put a solution to this coding problem together. The problem is this:




      Create a function that takes an array, finds the most often repeated element(s) within it and returns it/them in an array. The function should work for both integers and strings mixed together within the input list (e.g. [1, 1, "a"]).



      If there is a tie for highest occurrence, return both.



      Separate integers and strings in the result.



      If returning multiple elements, sort result alphabetically with numbers coming before strings.




      This is the solution I came up with:



      def highest_occurrence(arr)

      # Separate the unique values into individual sub-arrays
      x = rand(2**32).to_s(16)
      result = arr.sort do |a, b|
      a = a.to_s + x if a.is_a?(Numeric)
      b = b.to_s + x if b.is_a?(Numeric)
      a <=> b
      end.chunk_while {|a, b| a == b }.to_a

      # Get an array of all of the individual values with the max size,
      # Sort them by integers first, strings second
      result = result.select do |a2|
      a2.size == result.max_by(&:size).size
      end.map(&:uniq).flatten.sort_by { |v| v.class.to_s }

      end


      It passes these tests:



      p highest_occurrence(["a","a","b","b"]) == ["a","b"]
      p highest_occurrence([1,"a","b","b"]) == ["b"]
      p highest_occurrence([1,2,2,3,3,3,4,4,4,4]) == [4]
      p highest_occurrence(["ab","ab","b"]) == ["ab"]
      p highest_occurrence(["ab","ab","b","bb","b"]) == ["ab","b"]
      p highest_occurrence([3,3,3,4,4,4,4,2,3,6,7,6,7,6,7,6,"a","a","a","a"]) == [3,4,6,"a"]
      p highest_occurrence([2,2,"2","2",4,4]) == [2,4,"2"]


      I'd like to know whether there are better ways to solve some of the specific problems in this exercise. In particular, the requirement to sort strings and integers together without being able to convert the integers to strings in the sort block was an interesting one. I managed this by appending a random hex value (the same value) to each integer during the sort process. This seems a bit hackish, and I have the feeling it could be improved upon.



      I would also appreciate any other suggestions for how to do a cleaner job.









      share









      $endgroup$




      I put a solution to this coding problem together. The problem is this:




      Create a function that takes an array, finds the most often repeated element(s) within it and returns it/them in an array. The function should work for both integers and strings mixed together within the input list (e.g. [1, 1, "a"]).



      If there is a tie for highest occurrence, return both.



      Separate integers and strings in the result.



      If returning multiple elements, sort result alphabetically with numbers coming before strings.




      This is the solution I came up with:



      def highest_occurrence(arr)

      # Separate the unique values into individual sub-arrays
      x = rand(2**32).to_s(16)
      result = arr.sort do |a, b|
      a = a.to_s + x if a.is_a?(Numeric)
      b = b.to_s + x if b.is_a?(Numeric)
      a <=> b
      end.chunk_while {|a, b| a == b }.to_a

      # Get an array of all of the individual values with the max size,
      # Sort them by integers first, strings second
      result = result.select do |a2|
      a2.size == result.max_by(&:size).size
      end.map(&:uniq).flatten.sort_by { |v| v.class.to_s }

      end


      It passes these tests:



      p highest_occurrence(["a","a","b","b"]) == ["a","b"]
      p highest_occurrence([1,"a","b","b"]) == ["b"]
      p highest_occurrence([1,2,2,3,3,3,4,4,4,4]) == [4]
      p highest_occurrence(["ab","ab","b"]) == ["ab"]
      p highest_occurrence(["ab","ab","b","bb","b"]) == ["ab","b"]
      p highest_occurrence([3,3,3,4,4,4,4,2,3,6,7,6,7,6,7,6,"a","a","a","a"]) == [3,4,6,"a"]
      p highest_occurrence([2,2,"2","2",4,4]) == [2,4,"2"]


      I'd like to know whether there are better ways to solve some of the specific problems in this exercise. In particular, the requirement to sort strings and integers together without being able to convert the integers to strings in the sort block was an interesting one. I managed this by appending a random hex value (the same value) to each integer during the sort process. This seems a bit hackish, and I have the feeling it could be improved upon.



      I would also appreciate any other suggestions for how to do a cleaner job.







      ruby sorting





      share












      share










      share



      share










      asked 2 mins ago









      BobRodesBobRodes

      1212




      1212






















          0






          active

          oldest

          votes











          Your Answer





          StackExchange.ifUsing("editor", function () {
          return StackExchange.using("mathjaxEditing", function () {
          StackExchange.MarkdownEditor.creationCallbacks.add(function (editor, postfix) {
          StackExchange.mathjaxEditing.prepareWmdForMathJax(editor, postfix, [["\$", "\$"]]);
          });
          });
          }, "mathjax-editing");

          StackExchange.ifUsing("editor", function () {
          StackExchange.using("externalEditor", function () {
          StackExchange.using("snippets", function () {
          StackExchange.snippets.init();
          });
          });
          }, "code-snippets");

          StackExchange.ready(function() {
          var channelOptions = {
          tags: "".split(" "),
          id: "196"
          };
          initTagRenderer("".split(" "), "".split(" "), channelOptions);

          StackExchange.using("externalEditor", function() {
          // Have to fire editor after snippets, if snippets enabled
          if (StackExchange.settings.snippets.snippetsEnabled) {
          StackExchange.using("snippets", function() {
          createEditor();
          });
          }
          else {
          createEditor();
          }
          });

          function createEditor() {
          StackExchange.prepareEditor({
          heartbeatType: 'answer',
          autoActivateHeartbeat: false,
          convertImagesToLinks: false,
          noModals: true,
          showLowRepImageUploadWarning: true,
          reputationToPostImages: null,
          bindNavPrevention: true,
          postfix: "",
          imageUploader: {
          brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
          contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
          allowUrls: true
          },
          onDemand: true,
          discardSelector: ".discard-answer"
          ,immediatelyShowMarkdownHelp:true
          });


          }
          });














          draft saved

          draft discarded


















          StackExchange.ready(
          function () {
          StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fcodereview.stackexchange.com%2fquestions%2f215294%2fruby-sorting-an-assortment-of-strings-and-integers-together-while-keeping-them%23new-answer', 'question_page');
          }
          );

          Post as a guest















          Required, but never shown

























          0






          active

          oldest

          votes








          0






          active

          oldest

          votes









          active

          oldest

          votes






          active

          oldest

          votes
















          draft saved

          draft discarded




















































          Thanks for contributing an answer to Code Review Stack Exchange!


          • Please be sure to answer the question. Provide details and share your research!

          But avoid



          • Asking for help, clarification, or responding to other answers.

          • Making statements based on opinion; back them up with references or personal experience.


          Use MathJax to format equations. MathJax reference.


          To learn more, see our tips on writing great answers.




          draft saved


          draft discarded














          StackExchange.ready(
          function () {
          StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fcodereview.stackexchange.com%2fquestions%2f215294%2fruby-sorting-an-assortment-of-strings-and-integers-together-while-keeping-them%23new-answer', 'question_page');
          }
          );

          Post as a guest















          Required, but never shown





















































          Required, but never shown














          Required, but never shown












          Required, but never shown







          Required, but never shown

































          Required, but never shown














          Required, but never shown












          Required, but never shown







          Required, but never shown







          Popular posts from this blog

          Fairchild Swearingen Metro Inhaltsverzeichnis Geschichte | Innenausstattung | Nutzung | Zwischenfälle...

          Pilgersdorf Inhaltsverzeichnis Geografie | Geschichte | Bevölkerungsentwicklung | Politik | Kultur...

          Marineschifffahrtleitung Inhaltsverzeichnis Geschichte | Heutige Organisation der NATO | Nationale und...