Jump to content

The ultimate community for Ruby on Rails developers.


Photo

How do I get the sorting right in my algorithm's output?

ruby arrays

  • Please log in to reply
1 reply to this topic

#1 j.whittaker

j.whittaker

    Passenger

  • Members
  • 5 posts

Posted 28 December 2013 - 07:43 PM

I'm trying to build a simple algorithm to detect if two or more strings in an array matche a given list of words in a much larger array uniquely, as in, only one appearance of the characters in g, AND an unlimited amount of appearances of the vowels aeiou.

The consonants in the shorter array should remain in the same order as in the target.

I want to return an Array of Arrays with all the matches to each individual string in their own array:

 

    target = ["bs", 'tr', 'gl', 'bbss', 'sbb'] #etc...(Imagine if there were many more...)


    arr = ['base', 'true', 'glow', 'bees', 'bass', 'sabb', 'babss', 'glee', 'basatragl']

 

The expected output I want is this :

 

    #=> [['base', 'true', 'glee', 'babss', 'sabb'], ['bees', 'true', 'glee', 'babss', 'sabb']]

# for this example, this is the total amount of answers possible given array arr.

# all others either have more than 1 b or s, or contain other consonants.

 

What I tried:

 

  q = []


  for x in 0..s.length
  word
= arr.collect{ |z| [z, z.gsub(/[aeiou]/,"")] }.select{ |z| z[1] == s[x]}.collect{|z| z[0]}

  q << word
  end

  p q

 

 

 

I'm getting this output:

 

    [[\"base"\, \"bees"\], [\"true"\,], [\"glee"\]] ...

 

But I'm not sure how to get the output sorted more prettily, as in the expected, and with these blasted \ marks!  Perhaps my for loop needs to be changed?



#2 j.whittaker

j.whittaker

    Passenger

  • Members
  • 5 posts

Posted 31 December 2013 - 10:43 PM

My idea is to perhaps make a hash where:

 

hash = {dict_item_without_vowels: dict_item}

 

And fill up hash with all of the items in the dict, taking out their vowels.

 

Then make another hash like so:

 

hash2= {hash[dict_item_without_vowels] = example_item}

 

Whereever hash[dict_item_without_vowels] == example_item

 

Then call each of the hashes as needed to evaluate the given phrases in the arrays in example.

 

Am I making this too complicated or is there a simpler way?







Also tagged with one or more of these keywords: ruby, arrays

0 user(s) are reading this topic

0 members, 0 guests, 0 anonymous users