Re: Getting a random hash-table element?



On Thu, 29 Nov 2007 00:41:47 -0500, Ken Tilton wrote:

The nice thing about every form returning a value is:

(find-selected-symbol
(random (hash-table-count *my-table*)))

Initially, I've written this in one line. As that was too ugly, I've
introduced new variable in order to clarify things. But now it looks OK,
especially with this line break. :)

But we get more mileage out of code when it is parameterized. Sure, you
could rebind the special before each call and sometimes that is
appropriate (when other wise you are just forever having to pass the
table around) but by default I'd like to see a parameter:

(defun gre (h)
(fss (random (hash-table-count h))))

You're right, but in this situation *my-table* is the table used throughout
the whole program and passing it around as a parameter would be to
confusing. *my-table* is defined once, during initialization of parameters,
and used unmodified later.

Yep, and I like the counting down and testing for zero instead of
counting up with a second variable.

When you are ready (and don't wait too long) learn loop:

(defun gre-fss (h)
(loop for x downfrom (random (hash-table-count h))
for v being the hash-values of h
when (zerop x) return v))

Alright, this is the simplicity I needed! Learning loop is my next lesson.
:)

Although my solution works, maphash shouldn't be used like I did...

Thanks!
Tonci
--
"For millions of years mankind lived just like the animals
Then something happened which unleashed the power of our imagination
We learned to talk"
.



Relevant Pages

  • Re: DoEvents not working
    ... > to clarify the situation ... ... > I agree that iterating through 10000 records would not give me the ... But as posted in my initial Post, the loop ... > crptStatement (crystal report statement) appear) ...
    (microsoft.public.dotnet.languages.vb)
  • Re: How to cycle all possible permutations
    ... >than any mathematical knowledge. ... >I should think there is a for...next loop over a few layers that would ... Can you clarify a bit exactly what you want? ... auric underscore underscore at hotmail dot com ...
    (microsoft.public.excel.programming)
  • Re: list comprehension
    ... But after reading it, I was left with a question. ... at first I tried rearranging the one of the examples from the previously referenced document to clarify what was going on: ... then when I tried to rewrite it as a nested for loop, that's when I realized list comprehensions is a method of returning the calculation in the interior of a for loop as an assignment without requiring aggregation of results in a temporary variable. ... I would even settle for a wizard tool generating the first approximation for me. ...
    (comp.lang.python)
  • Re: For Loop Help
    ... Hope this helps to clarify. ... Craig ... > // To a for loop that changes the variable name so I don't have to list ... Prev by Date: ...
    (comp.lang.javascript)