Return Styles: Pseud0ch, Terminal, Valhalla, NES, Geocities, Blue Moon. Entire thread

Quick Question

Name: Anonymous 2009-11-03 2:36


public class MostOftenOccurring{
  public static int occursMostOften(int[] a){
    int[] b = new int[a.length];
    for (int i = 0; i < a.length; i++){
      b[i] = CountOccurrences.countOccurrences(a, a[i]);
    }
    for (int j = 0; j < b.length; j++){
      if (Maximum.maximum(b) == b[j]){
        return b[j];
      }
    }
    return 666; //I did this to make the compiler happy
  }
  public static void main(String[] args){
    int[] testArray = {1};
    System.out.println(occursMostOften(testArray));
  }
}



Is there any way that return 666; could ever be executed?

Name: Anonymous 2009-11-03 14:33


(defun list->frequency-hash-table (list &key (test #'eql))
  "Given a list, returns a hashtable keyed by each element in the list,
    and the values are each element's frequency in the list."
  (let ((counts (make-hash-table :test test)))   
    (dolist (i list counts)
      (symbol-macrolet ((hash (gethash i counts)))
        (if hash (incf hash) (setf hash 1))))))

(defun hashtable->alist (ht)
  "Converts a hashtable to an association list"
  (let (alist)
    (maphash #'(lambda (key val)
                 (push (cons key val) alist))
             ht)
    alist))

(defun max-occurances-pair (list)
  "Returns a cons pair whose car is the most frequent element, and whose cdr is the number of occurances"
  (first (sort (hashtable->alist (list->frequency-hash-table list)) #'> :key #'cdr)))

(defun max-occurances (list)
  "Returns two values, the most frequent element, and the number of occurances"   
  (destructuring-bind (val . count) (max-occurances-pair list)
    (values val count)))


Anyone having a more elegant solution is welcome to post it. I can't think of one without writing some functions for mapping/searching over hash tables. I believe there's a few utility libraries which already have code for this, but I didn't bother looking them up now.

Newer Posts
Don't change these.
Name: Email:
Entire Thread Thread List