I wanted to write the code for comparing the size of two lists. I made use of the length and wrote this down.
(define (same-size-matrix? mtrx1 mtrx2)
(equal? (length mtrx1) (length mtrx2))).
I thought this was going to work for me, but I found out it only checks the overall length, not the sublist. For example it returns true when it compares for. ‘((1 2 3 4) (4 5 6 6) (6 7 8 9)) and ‘(( 5 4) (3 2) (7 1)), but it’s supposed to return false, because the first has 4 values within the list and the second has only two even though they both overally have same length. How do I go about this. Any help would be appreciated.
Try this instead:
Notice that in your solution you’re comparing the total length of each list (the number of rows in the matrix), but ignoring the length of each sublist (the number of columns for each row in the matrix). In my soultion, first we calculate the length of each sublist and after that we check if all the lengths are equal. For example, take this input:
First the
same-size-matrix?evaluates this expression, which finds the length of each sublist inmtrx1. It’s necessary to check all the lengths, not just the first one, in case we’re dealing with a jagged array:And then we have this expression, which performs the same operation for
mtrx2:Finally, we compare the two lists of lengths (in fact: the number of columns per row), returning the expected result:
Notice that the last comparison will also detect if the lists are of different size, in case the matrices have a different number of rows.