Would it be possible to use a set of integers instead of bytes and avoid the casting? (not that I think it will make a difference but casting can theoretically lead to problems).
No, sets in Pascal are limited to 256 elements, i.e. set of Byte is the largest set possible, if you use the set constructor and operators that are built-in to the language. (You could of course devise your own implementation of a set of Integers, but it would be slow compared to the built-in Pascal implementation of the smaller sized set).
Casting is OK as long as you know what you are doing. In this case casting from Integer to Byte is perfectly OK because we know that the r (Integer) value will never be negative or greater than 40. i.e. it is
always within Byte range. So the cast to Byte is always safe. As I said, it would have been better really to declare r as Byte in the first place from an educational point of view. I unconsciously declared it as Integer because I know that native types are usually processed fastest. But in this case speed is not an issue at all, and clarity of code should have led me to declare r as a Byte (which would have avoided this discussion).