Register to post in forums, or Log in to your existing account
 

Play RetroMUD
Post new topic  Reply to topic     Home » Forums » CMUD General Discussion
GeneralStonewall
Magician


Joined: 02 Feb 2004
Posts: 364
Location: USA

PostPosted: Mon Nov 23, 2009 10:00 pm   

[Completed] Sort database keys by values function
 
I wrote this after needing a way to sort my database keys by their values. What it does is takes a database variable and returns its keys in order by their values. You can then use it in a loop to display the database in order. You might have to change how the local variables are setup depending on which version of CMUD you're using.

XML:
Code:
<?xml version="1.0" encoding="ISO-8859-1" ?>
<cmud>
  <func name="sort_db_keys_by_val" copy="yes">
    <value>#local $value $key $j $keys $vals
$keys = %dbkeys( $database)
$vals = %dbvalues( $database)
#loop 2,%numitems( $keys) {
  $value = %item( $vals, %i )
  $key = %item( $keys, %i )
  $j = %i - 1
  #while ($j >= 1 and %item( $vals, $j ) > $value) {
    $vals.%eval( $j + 1 ) = $vals.$j
    $keys.%eval( $j + 1 ) = $keys.$j
    $j = $j - 1
    }
  $vals.%eval( $j + 1 ) = $value
  $keys.%eval( $j + 1 ) = $key
  }
#return $keys</value>
    <arglist>$database</arglist>
  </func>
</cmud>


zScript:
Code:
#local $value $key $j $keys $vals
$keys = %dbkeys( $database)
$vals = %dbvalues( $database)
#loop 2,%numitems( $keys) {
  $value = %item( $vals, %i )
  $key = %item( $keys, %i )
  $j = %i - 1
  #while ($j >= 1 and %item( $vals, $j ) > $value) {
    $vals.%eval( $j + 1 ) = $vals.$j
    $keys.%eval( $j + 1 ) = $keys.$j
    $j = $j - 1
    }
  $vals.%eval( $j + 1 ) = $value
  $keys.%eval( $j + 1 ) = $key
  }
#return $keys


Example:
Code:
#forall @sort_db_keys_by_val(@dbvar) {#print {Key: %i Value: %db(@dbvar, %i)}}
Reply with quote
Display posts from previous:   
Post new topic   Reply to topic     Home » Forums » CMUD General Discussion All times are GMT
Page 1 of 1

 
Jump to:  
You cannot post new topics in this forum
You cannot reply to topics in this forum
You cannot edit your posts in this forum
You cannot delete your posts in this forum
You cannot vote in polls in this forum

© 2009 Zugg Software. Hosted by Wolfpaw.net