In: Computer Science
RACKET
a) Write a recursive function (gen-list start end). This function will generate a list of consecutive integers, from start to end. If start > end then an empty list is generated. For example: (gen-list 1 5) ---> (1 2 3 4 5)
b) write a recursive function pair-sum? that takes an integer sequence as generated by the gen-list function in exercise 4 above. This function tests whether any two adjacent values in the given list sum to the given val. For example,
(pair-sum? '(1 2 3) 3) ---> #t since 1+2=3. Similarly,
(pair-sum? (gen-list 1 100) 1000) ---> #f since no two adjacent integers in the range 1 to 100 can sum to 1000.
You must use recursion, and not iteration. Please include explanation thanks.
Solution :-
a)
Previous Version:
//suppose start=n and end=N
void gen_list(int n, int N) // This gen_list will
generate list of consecutive integers, from start (n) to
end (N)
{
if(n>N) //Start >End
{
printf("The list is empty"); //It will print empty list
return; // return to main()
}
if (n <= N) //Start <End
{
printf("%d,", n); //print the number
n++; // increment n
gen_list(n,N); //recursion call
}
else
return; // return to main()
}
In RACKET:
(define (gen-list Start End)
(if (> Start End) // check if Start grearted than End or
not
#f
(cond ((<= Start End) // check if Start less than End or
not
(gen-list Start (- End 1)) //Call to recursion
(display End) //show the output
(display " ")))))
b)
Previous Version:
int i=1, int j=1; //intilialize to variables
void pairsum?(int a[], int i, int j, int sum, int n) //list of
integers are stored in the array a, sum represents sum of two
numbers and n is the numbe of elements in the array
{
int k;
if(i>n || j>n) //required sum not exists
{
printf("#f");
return; // return to main()
}
k=a[i]+a[j];
if(k==sum)
{
printf("#t");
return; // return to main()
}
else{
pairsum?(a,i+1,j+1,sum,n); //call to recursion after
incrementing i and j
}
}
In RACKET:
(define (pair-sum? 1st s) // 1st is the input list of
numbers and s is the required sum
(if (null? (cdr lst)) // checking is list is null or not
#f
(if (= (+ (car lst) (car (cdr lst))) s) // checking the sum of
paires is equal to s or not
#t
(pair-sum? (cdr lst) s)))) // Call to recursion
Thank you.... if any Quire's Feel free to ask me Sir