Question

write a function to generate test data. The common-lisp function (random n) will return a random...

write a function to generate test data.  The common-lisp function (random n) will return a random number in the range zero to n. there is a problem of number partitioning.  Given a set of  integerts, the task is to divide them into two mutually exclusive and  collectively exhaustive subsets, so that the sums of the numbers in each subset  are as nearly equal as possible.  For example, given the set (1 4 9 16 25), an  optimal partition divides the numbers into the sets (1 25) and (4 9 16).  Since  the sum of the numbers in the first set is 26, and the sum of the numbers in  the second set is 29, the difference of the sums is 3, and this is the smallest  difference that can be achieved in this case. the number partitioning problems generally become more difficult with increasing magnitude of the numbers, so be sure to test your program against integers at least as large as a million.  Note that it is feasible to optimally solve instances with very large numbers of integers if the integers are small.
0 0
Add a comment Improve this question Transcribed image text
Answer #1

;;;; -*- Mode: Lisp; indent-tabs-mode: nil -*-

(in-package :it.bese.fiveam)

;;;; ** Random (QuickCheck-ish) testing

;;;; FiveAM provides the ability to automatically generate a
;;;; collection of random input data for a specific test and run a
;;;; test multiple times.

;;;; Specification testing is done through the FOR-ALL macro. This
;;;; macro will bind variables to random data and run a test body a
;;;; certain number of times. Should the test body ever signal a
;;;; failure we stop running and report what values of the variables
;;;; caused the code to fail.

;;;; The generation of the random data is done using "generator
;;;; functions" (see below for details). A generator function is a
;;;; function which creates, based on user supplied parameters, a
;;;; function which returns random data. In order to facilitate
;;;; generating good random data the FOR-ALL macro also supports guard
;;;; conditions and creating one random input based on the values of
;;;; another (see the FOR-ALL macro for details).

;;;; *** Public Interface to the Random Tester

(defparameter *num-trials* 100
"Number of times we attempt to run the body of the FOR-ALL test.")

(defparameter *max-trials* 10000
"Number of total times we attempt to run the body of the
FOR-ALL test including when the body is skipped due to failed
guard conditions.
Since we have guard conditions we may get into infinite loops
where the test code is never run due to the guards never
returning true. This second run limit prevents that.")

(defmacro for-all (bindings &body body)
"Bind BINDINGS to random variables and test BODY *num-trials* times.
BINDINGS is a list of binding forms, each element is a list
of (BINDING VALUE &optional GUARD). Value, which is evaluated
once when the for-all is evaluated, must return a generator which
be called each time BODY is evaluated. BINDING is either a symbol
or a list which will be passed to destructuring-bind. GUARD is a
form which, if present, stops BODY from executing when IT returns
NIL. The GUARDS are evaluated after all the random data has been
generated and they can refer to the current value of any
binding. NB: Generator forms, unlike guard forms, can not contain
references to the bound variables.
Examples:
(for-all ((a (gen-integer)))
    (is (integerp a)))
(for-all ((a (gen-integer) (plusp a)))
    (is (integerp a))
    (is (plusp a)))
(for-all ((less (gen-integer))
            (more (gen-integer) (< less more)))
    (is (<= less more)))
(for-all (((a b) (gen-two-integers)))
    (is (integerp a))
    (is (integerp b)))"
(with-gensyms (test-lambda-args)
    `(perform-random-testing
      (list ,@(mapcar #'second bindings))
      (lambda (,test-lambda-args)
        (destructuring-bind ,(mapcar #'first bindings)
            ,test-lambda-args
          (if (and ,@(delete-if #'null (mapcar #'third bindings)))
              (progn ,@body)
              (throw 'run-once
                (list :guard-conditions-failed))))))))

;;;; *** Implementation

;;;; We could just make FOR-ALL a monster macro, but having FOR-ALL be
;;;; a preproccessor for the perform-random-testing function is
;;;; actually much easier.

(defun perform-random-testing (generators body)
(loop
     with random-state = *random-state*
     with total-counter = *max-trials*
     with counter = *num-trials*
     with run-at-least-once = nil
     until (or (zerop total-counter)
               (zerop counter))
     do (let ((result (perform-random-testing/run-once generators body)))
          (ecase (first result)
            (:pass
             (decf counter)
             (decf total-counter)
             (setf run-at-least-once t))
            (:no-tests
             (add-result 'for-all-test-no-tests
                         :reason "No tests"
                         :random-state random-state)
             (return-from perform-random-testing nil))
            (:guard-conditions-failed
             (decf total-counter))
            (:fail
             (add-result 'for-all-test-failed
                         :reason "Found failing test data"
                         :random-state random-state
                         :failure-values (second result)
                         :result-list (third result))
             (return-from perform-random-testing nil))))
     finally (if run-at-least-once
                 (add-result 'for-all-test-passed)
                 (add-result 'for-all-test-never-run
                             :reason "Guard conditions never passed"))))

(defun perform-random-testing/run-once (generators body)
(catch 'run-once
    (bind-run-state ((result-list '()))
      (let ((values (mapcar #'funcall generators)))
        (funcall body values)
        (cond
          ((null result-list)
           (throw 'run-once (list :no-tests)))
          ((every #'test-passed-p result-list)
           (throw 'run-once (list :pass)))
          ((notevery #'test-passed-p result-list)
           (throw 'run-once (list :fail values result-list))))))))

(defclass for-all-test-result ()
((random-state :initarg :random-state)))

(defclass for-all-test-passed (test-passed for-all-test-result)
())

(defclass for-all-test-failed (test-failure for-all-test-result)
((failure-values :initarg :failure-values)
   (result-list :initarg :result-list)))

(defgeneric for-all-test-failed-p (object)
(:method ((object for-all-test-failed)) t)
(:method ((object t)) nil))

(defmethod reason ((result for-all-test-failed))
(format nil "Falsifiable with ~S" (slot-value result 'failure-values)))

(defclass for-all-test-no-tests (test-failure for-all-test-result)
())

(defclass for-all-test-never-run (test-failure for-all-test-result)
())

;;;; *** Generators

;;;; Since this is random testing we need some way of creating random
;;;; data to feed to our code. Generators are regular functions which
;;;; create this random data.

;;;; We provide a set of built-in generators.

(defun gen-integer (&key (max (1+ most-positive-fixnum))
                         (min (1- most-negative-fixnum)))
"Returns a generator which produces random integers greater
than or equal to MIN and less than or equal to MAX."
(lambda ()
    (+ min (random (1+ (- max min))))))

(defun gen-float (&key bound (type 'short-float))
"Returns a generator which produces floats of type TYPE. BOUND,
if specified, constrains the results to be in the range (-BOUND,
BOUND)."
(lambda ()
    (let* ((most-negative (ecase type
                            (short-float most-negative-short-float)
                            (single-float most-negative-single-float)
                            (double-float most-negative-double-float)
                            (long-float most-negative-long-float)))
           (most-positive (ecase type
                            (short-float most-positive-short-float)
                            (single-float most-positive-single-float)
                            (double-float most-positive-double-float)
                            (long-float most-positive-long-float)))
           (bound (or bound (max most-positive (- most-negative)))))
      (coerce
       (ecase (random 2)
         (0 ;; generate a positive number
          (random (min most-positive bound)))
         (1 ;; generate a negative number
          (- (random (min (- most-negative) bound)))))
       type))))

(defun gen-character (&key (code-limit char-code-limit)
                           (code (gen-integer :min 0 :max (1- code-limit)))
                           (alphanumericp nil))
"Returns a generator of characters.
CODE must be a generator of random integers. ALPHANUMERICP, if
non-NIL, limits the returned chars to those which pass
alphanumericp."
(lambda ()
    (loop
       for count upfrom 0
       for char = (code-char (funcall code))
       until (and char
                  (or (not alphanumericp)
                      (alphanumericp char)))
       when (= 1000 count)
       do (error "After 1000 iterations ~S has still not generated ~:[a valid~;an alphanumeric~] character :(."
                 code alphanumericp)
       finally (return char))))

(defun gen-string (&key (length (gen-integer :min 0 :max 80))
                        (elements (gen-character))
                        (element-type 'character))
"Returns a generator which produces random strings. LENGTH must
be a generator which produces integers, ELEMENTS must be a
generator which produces characters of type ELEMENT-TYPE."
(lambda ()
    (loop
       with length = (funcall length)
       with string = (make-string length :element-type element-type)
       for index below length
       do (setf (aref string index) (funcall elements))
       finally (return string))))

(defun gen-list (&key (length (gen-integer :min 0 :max 10))
                      (elements (gen-integer :min -10 :max 10)))
"Returns a generator which produces random lists. LENGTH must be
an integer generator and ELEMENTS must be a generator which
produces objects."
(lambda ()
    (loop
       repeat (funcall length)
       collect (funcall elements))))

(defun gen-tree (&key (size 20)
                      (elements (gen-integer :min -10 :max 10)))
"Returns a generator which produces random trees. SIZE controls
the approximate size of the tree, but don't try anything above
30, you have been warned. ELEMENTS must be a generator which
will produce the elements."
(labels ((rec (&optional (current-depth 0))
             (let ((key (random (+ 3 (- size current-depth)))))
               (cond ((> key 2)
                      (list (rec (+ current-depth 1))
                            (rec (+ current-depth 1))))
                     (t (funcall elements))))))
    (lambda ()
      (rec))))

(defun gen-buffer (&key (length (gen-integer :min 0 :max 50))
                        (element-type '(unsigned-byte 8))
                        (elements (gen-integer :min 0 :max (1- (expt 2 8)))))
(lambda ()
    (let ((buffer (make-array (funcall length) :element-type element-type)))
      (map-into buffer elements))))

(defun gen-one-element (&rest elements)
(lambda ()
    (nth (random (length elements)) elements)))

;;;; The trivial always-produce-the-same-thing generator is done using
;;;; cl:constantly.

Add a comment
Know the answer?
Add Answer to:
write a function to generate test data. The common-lisp function (random n) will return a random...
Your Answer:

Post as a guest

Your Name:

What's your source?

Earn Coins

Coins can be redeemed for fabulous gifts.

Not the answer you're looking for? Ask your own homework help question. Our experts will answer your question WITHIN MINUTES for Free.
Similar Homework Help Questions
  • Write the function below in scheme/lisp programming language. Drracket Exercise: It is well known that n^2...

    Write the function below in scheme/lisp programming language. Drracket Exercise: It is well known that n^2 is equal to the sum of the first n odd numbers. For example, 16 = 4^2 = 7 + 5 + 3 + 1. Write a function that takes as input a natural number, n, and that returns the square of its input by adding the first n odd numbers. Your code may not contain delayed operations and must use accumulative recursion.

  • The problem demonstrates the use of the random number generator to recover previously generated random numbers Write a function called randi test that takes two scalar positive integer arguments maxi...

    The problem demonstrates the use of the random number generator to recover previously generated random numbers Write a function called randi test that takes two scalar positive integer arguments maxi and n, and retums two output arguments: a row vector of n2 elements and and n-by-n matrix. The two output arguments must contain the exact same set of random integers that fall between 1 and maxi Do this using the random number genertor, not by reshaping the data Example n,v-randi...

  • 3) Create a vector of noisy data by adding a trigonometric function to a random number,...

    3) Create a vector of noisy data by adding a trigonometric function to a random number, starting from your month of birth up to last 5 digits of your student ID number. So, a student with an ID number of 110030110 should create random numbers up to 30110. Calculate statistical values of the random data and print them to the command window in a tabular format. Smooth that noisy data with a moving average filter using a step size of...

  • Write a recursive function called freq_of(letter, text) that finds the number of occurrences of a specified...

    Write a recursive function called freq_of(letter, text) that finds the number of occurrences of a specified letter in a string. This function has to be recursive; you may not use loops!   CodeRunner has been set to search for keywords in your answer that might indicate the use of loops, so please avoid them. For example: Test Result text = 'welcome' letter = 'e' result = freq_of(letter, text) print(f'{text} : {result} {letter}') welcome : 2 e and A list can be...

  • 1. Implement a tostring() member function. This function will return a string representation of the LargeInteger....

    1. Implement a tostring() member function. This function will return a string representation of the LargeInteger. You should probably used string streams to implement this function. Note that the digits of the large integer are stored in reverse of their display order, e.g. the 1's place (100 ) is in index 0 of digits, the 10's place (101 ) is in index 1, etc. 2. Implement a second constructor for the LargeInteger. This constructor will be used to construct a...

  • You may import the following library functions in your module: from fractions import gcd from math...

    You may import the following library functions in your module: from fractions import gcd from math import log from math import floor You may also use: • the .bit_length() method to efficiently obtain the bit length of an integer, • the abs() function for computing the absolute value of an integer, • and the // operator for integer division (you should avoid using / because it does not work for very large integers). Implement the following Python functions. These functions...

  • Write a C++ program named, gradeProcessor.cpp, that will do the following tasks: -Print welcome message -Generate...

    Write a C++ program named, gradeProcessor.cpp, that will do the following tasks: -Print welcome message -Generate the number of test scores the user enters; have scores fall into a normal distribution for grades -Display all of the generated scores - no more than 10 per line -Calculate and display the average of all scores -Find and display the number of scores above the overall average (previous output) -Find and display the letter grade that corresponds to the average above (overall...

  • Implement the following Python functions. These functions take advantage of the generalized Euclid's lemma to make...

    Implement the following Python functions. These functions take advantage of the generalized Euclid's lemma to make it possible to generate a random number within a specified range. Your implementations must be extremely efficient, and must handle very large inputs, as shown in the examples below. Implementations that perform exhaustive, exponential-time searches will receive no credit. a. Implement a function closest(t, ks) that takes two arguments: a target integer t and a list of integers ks. The function should return the...

  • 1) Continuous random variables are obtained from data that can be measured rather than counted. A)...

    1) Continuous random variables are obtained from data that can be measured rather than counted. A) True B) False 2) Discrete variables have values that can be measured. A) True B) False 3) Determine whether the random variable described is discrete or continuous. The number of minutes you must wait in line at the grocery store A) continuous B) discrete 4) Determine whether the random variable described is discrete or continuous. The total value of a set of coins A)...

  • MATLAB Create a function that provides a definite integration using Simpson's Rule Problem Summar This example demo...

    MATLAB Create a function that provides a definite integration using Simpson's Rule Problem Summar This example demonstrates using instructor-provided and randomized inputs to assess a function problem. Custom numerical tolerances are used to assess the output. Simpson's Rule approximates the definite integral of a function f(x) on the interval a,a according to the following formula + f (ati) This approximation is in general more accurate than the trapezoidal rule, which itself is more accurate than the leftright-hand rules. The increased...

ADVERTISEMENT
Free Homework Help App
Download From Google Play
Scan Your Homework
to Get Instant Free Answers
Need Online Homework Help?
Ask a Question
Get Answers For Free
Most questions answered within 3 hours.
ADVERTISEMENT
ADVERTISEMENT