How many three-digit numbers are there where the middle digit is lower than both the first digit and the third digit?
My reaction to this is to loop through all of the numbers 100-999 and count the ones that pass the test.
(yes, lines 40 and 45 look a little inelegant with that repetition, but I tried it with a goto (yuk) and gosub and this was the shortest and neatest of my variations. I wanted to print the qualifying numbers as well as inc'ing the count).
I remember a very similar question in the past, involving 3-digit numbers. I think it was Mr Beckett who used a single loop in Forth and wrote words to separate out the hundreds, tens and units. (Seemed a little counter-intuitive to me but Forth doesn't allow you access to the indices of three nested loops). So I thought I'd give that a go to see whether it would be more elegant than the BASIC version.
Here are my 'hundreds', 'tens' and 'units' words (made easier as the default type in Ace Forth is an integer) and the 'run' loop. The zero at the start is my counter, conveniently at the top of the stack at the point where I want to increment it.
As you can see, it arrived at the same answer, 285, so I'm sure that's the right answer.
This leaves me very curious about how the question setter expected people to solve this, if not by an automated 'loop and count'.
Looking at the numbers that both programs produce, it might be possible to go through and reason it out - ie "in the 100's, only 10x will qualify, so that's 9" and so on, but that seems very longwinded.
Any thoughts on this?
Do you have any alternative programs in other languages / other systems?
Update:
Thanks to people joining in on twitter, we had this serious improvement on the basic program:
10 for i = 0 to 8
20 for j = i+1 to 9
30 for k = i+1 to 9
.. which removes the need for a test as it only gives numbers where hundreds and units are > tens
Following on from this, and thanks to several friends, it became clear that we can use:
1^2 + 2^2 etc
The clearest explanation for this is from Mr A, who said:
Middle = 8, Perms = 1 (989)
Middle = 7, Perms = 4 (878, 879, 978, 979)
Middle = 6, Perms = 9 (767, 768, 769, 867, 868, 869, 967, 968, 969)
Hi. Loving the Quiz questions (and answers). Do you mind me asking where they are published?
ReplyDeleteI have built an RC65(C)02 with Tali Forth 2 (65c02 only) so keen to have a go (it's just too tempting to have a peek at your answers first).
Hi Reggie, glad you enjoy these. The quiz is put together by a friend of a friend, I'm not sure of the protocol for giving the details publicly, but if you write to me at shieladixon@gmail.com I'll let you know.
DeleteI'd love to know more about your computer, have you published the details anywhere?