0

I have the following array

prime_arr = [2,3,5,7,11,13]

and I need to check whether the array has 3, 5 7 and return the value(s) differ based on presence

If it has 3 alone return "Yes" and 5 alone return "it is " and 7 alone return "done" and

If it has [3,5] return "Yes it is "

If it has [3,5,7] return "Yes it is done"

The return value should differ based on combination

Thanks in advance.

1
  • What about the other three combinations? Commented Jan 5, 2015 at 8:03

3 Answers 3

2

Since this looks a lot like homework (and since no one here is paid to write your code for you), I'm not going to give you the actual answer. I will however give you some pointers to pieces of the puzzle - hopefully you'll be able to piece them together.

You can find the intersection between two arrays using the #& method. So:

prime_arr = [2,3,5,7,11,13]
# => [2, 3, 5, 7, 11, 13]
prime_arr & [3]
# => [3]
prime_arr & [3,5]
# => [3, 5]
prime_arr & [3,5,7]
# => [3, 5, 7]
prime_arr & [4]
# => []

A case statement can toggle on Array values, like so:

a = [1,2]
case a
  when [1]; "just one"
  when [1,2]; "both"
end
# => "both"

Good luck!

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks for help but here we need to write the cases for every combination where the code doesnot smell good.. :(
0

Not sure about the other three cases you haven't made clear, so I am guessing.

[[3, 5, 7], ["Yes ", "it is ", "done"]]
.transpose.each.with_object(""){|(i, w), s| s << w if prime_arr.include?(i)}

1 Comment

Firstly, thanks for help Actually I am getting the Prime Factors of given number in to one array.(prime_arr) If it has other than specified values it should return the Given number.
0
words = ['Yes', 'it is', 'done']
prime_arr = [2, 3, 5, 7, 11, 13]
target = [3, 5, 7]

words.take((prime_arr & target).size).join(" ")

Edited:

prime_arr = [2, 3, 5, 7, 11, 13]
mapping = {
  [3] => 'Yes',
  [3, 5] => 'Yes it is',
  [3, 5, 7] => 'Yes it is done'
}

mapping[prime_arr & [3, 5, 7]] # => 'Yes it is done'
mapping[prime_arr & [3, 5]] # => 'Yes it is'
mapping[prime_arr & [3]] # => 'Yes'

You get a nil when none of the keys in mapping matches.

2 Comments

Thanks for answer.But it fails when it is 5 and 7 alone it returns "Yes" as we are depending on the size.any alternate appreciated
Ah, did not take this into account. Will edit the answer

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.