1

I want the following block of code to return value not equal to 0 or n. But sometimes it returns values equal to 0.

def get_random(n, num) do   
   random = returns some number
   IO.puts random
   if random == n or random == 0 do
      get_random(n, num)
   end
   random
end
2
  • shouldn't it be random instead of ran in your if statement? Commented Oct 6, 2017 at 7:47
  • I have changed the variable name. Thanks. Commented Oct 6, 2017 at 7:52

1 Answer 1

1

You didn't set random variable second time.

Fixed code:

defmodule GetRandom do
  def get_random(n, num) do
    random = Enum.random(0..num)
    IO.puts random
    random = if random == n or random == 0 do
      get_random(n, num)
    else
      random
    end
    random
  end
end

This code can be simplified. First, if Enum.random is used, you don't need to exclude 0 after call. Just exclude it from range.

Also, use implicit value return. You don't need to set random variable second time if it is in the end of the function.

defmodule GetRandom do
  def get_random(n, num) do
    random = Enum.random(1..num)
    IO.puts random
    if random == n do
      get_random(n, num)
    else
      random
    end
  end
end
Sign up to request clarification or add additional context in comments.

Comments

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.