scheme - How to make pairs from a numeric list based on cardinality? -
i have list '(1 2 1 1 4 5)
, want output list '((1 3)(2 1)(4 1)(5 1))
. have written small code stuck how calculate cardinality each number , put pair in list. can please @ code , give ideas? thanks.
(define set2bags (lambda (randlist) (cond ((null? randlist) '()) (else (sort randlist) (makepairs randlist))))) (define makepairs (lambda (inlist) (let ((x 0)) ((newlist '())) (cond ((zero? (car inlist)) '()) (else (eq? (car inlist)(car (cdr inlist))) (+ x 1) (makepairs (cdr inlist)) (append newlist (cons (car inlist) x)))))))
your current solution incorrect - doesn't compile. let's start again scratch, using named let
traversing input list:
(define set2bags (lambda (randlist) (cond ((null? randlist) '()) (else (makepairs (sort randlist >)))))) (define makepairs (lambda (inlist) (let loop ((lst inlist) (prv (car inlist)) (num 0) (acc '())) (cond ((null? lst) (cons (list prv num) acc)) ((= (car lst) prv) (loop (cdr lst) prv (add1 num) acc)) (else (loop (cdr lst) (car lst) 1 (cons (list prv num) acc)))))))
now works expected:
(set2bags '(1 2 1 1 4 5)) => '((1 3) (2 1) (4 1) (5 1))
the trick keeping counter cardinality (i called num
), , incrementing long same previous element (i named prv
) equals current element. whenever find different element, add new pair output list (called acc
) , reset previous element , counter.
Comments
Post a Comment