News:

Printed Amstrad Addict magazine announced, check it out here!

Main Menu

BASIC program that prints numbers in descending order

Started by DRobert, 17:29, 09 November 20

Previous topic - Next topic

0 Members and 1 Guest are viewing this topic.

DRobert

Hi to all
I have only just signed up to this forum and looking to learn from experience of others more proficient in these matters.
After discovering my old Amstrad 464+ (that had been mothballed over 25 years ago) I was surprised to find that my very simple programmes (saved on a cassette tape) still worked.   This has fired my enthusiasm for the Amstrad and wondered if anyone could help me with regards to my tentative attempts at programming.
I enjoy sports and some of my simple programmes are based around soccer etc.  All have been on screen text based images as opposed to graphics.   Much of what I have done so far is based on "GOTOs" which I realise from comments on here are generally frowned upon.   However my main stumbling block at the moment is finding an appropriate block of "BASIC" coding that can read variable numbers (linked to STRING$) and then reproduce them / PRINT in a descending or ascending order.  I thought I had read many years ago that, for example, a business could prepare a list of employees and their salaries in some sort of number order?
I have managed a simple BASIC program with 3 variables (ie a,b,c) but have had to type this in a 'long hand" fashion.  Even for just 3 variables there is a fair amount of coding and to increase it by one or two more increases this exponentially (let alone having a list of 20 variables).   I have googled for the last week or so and although there are programs in other computing languages which carry out this function I cannot find anything in Amstrad BASIC which performs this SORT function.

I would appreciate any comments which will lead to my solution of this issue.   Thanks for reading.

eto

You are looking for a sorting algorithm. The easiest ist probably Bubble Sort and you can use Arrays (DIM) in Basic to achieve that.

I also found this thread where a DSK image with lots of BASIC examples is included and one of the examples seems to be a Bubble Sort implementation.
http://www.cpcwiki.eu/forum/cpcwiki-discussion/acu-type-ins-project/msg138542/#msg138542


SRS


DRobert

Thanks very much for your prompt replies.  I'll give them a try and let you know how I go on. 

GeoffB17

Hello,

Happy to help if I can.

I spent many years doing 'business' type programming, mainly using dbase/Clipper type systems, for accounts/stock/wholesale type businesses.   Not in BASIC, but I keep on using various BASIC variants for specific jobs.

Yes, things are a LOT easier when the language you're using has the right things built in, esp sorting/indexing etc.   However, the Bubble Sort is easy to implement and is fine for smaller data sets, but if your data gets bigger it's well worth trying the more complex Quick Sort method.   There are variants of both readily available in BASIC that will work fine for you.

Don't worry about GOTO - I still use them now.   yes, they can lead to spaghetti code that jomps agout all over the place making a program much more difficult to follow, and fix when it goes wrong or needs improving, but they're perfectly OK if used with care, and with suitable comments.   It's just about style.

As for your program, I'd suggest that you create a data file as a .txt file.   Put your formatted data into this file, order doesn't matter.   Formatting DOES.   Then write your prog(s) to read the data from the file, process it however you need, and then maybe write the data back to a new file.   You can add extra data to the file as required, you may need to read ALL the data into your prog, but you don't need to do anything with more than you need to.   Depending on the data, you might use more than one file to store it (main or header records, with separate 'transactions').

Geoff

DRobert

Thank you Geoff for your kind response and encouraging comments.


I am very much at a preliminary stage in all of the above but have spent a lot of time reading and watching you tube clips trying to "find my level".  I've spent time today trying to understand the principles of "bubblesort" in conjunction with swotting up on the simple BASIC commands that I last used over 25 years ago.  Its tempting to try and run before walking but that is virtually impossible to do without putting in the effort initially. 


Thanks once again to you and the other guys above for helping me towards the solutions I am looking for.

GUNHED

Using GOTOs work, but for BASIC the 464 Plus has the nice command ON x GOTO line1, line2, line3 ... see manual. Also GOSUB is helpful.
http://futureos.de --> Get the revolutionary FutureOS (Update: 2023.11.30)
http://futureos.cpc-live.com/files/LambdaSpeak_RSX_by_TFM.zip --> Get the RSX-ROM for LambdaSpeak :-) (Updated: 2021.12.26)

goksteroo

The most efficient method is going to depend on the type and range of data you are sorting - is it purely numerical? Is it integer or real numbers? What is the range (or potential range) of the numbers? How are the array/s holding all the data organized?

DRobert

Quote from: GUNHED on 23:34, 10 November 20
Using GOTOs work, but for BASIC the 464 Plus has the nice command ON x GOTO line1, line2, line3 ... see manual. Also GOSUB is helpful.


Ah thanks,  I'll have a play around with those options.  I will read and review the manual to get my knowledge up to speed from what is currently a slow start.

DRobert

Quote from: goksteroo on 07:40, 11 November 20
The most efficient method is going to depend on the type and range of data you are sorting - is it purely numerical? Is it integer or real numbers? What is the range (or potential range) of the numbers? How are the array/s holding all the data organized?


Thanks for your comments.  To be honest I'm only just discovering the potential for writing simple programs for a bit of fun and to keep my brain cells active now I have retired (can only do so much soduko etc).   


I cant honestly say exactly what data will be sorted.   I would imagine that any sports type programs would involve statistics and figures such as "teams and league tables" plus "individual names plus goals scored etc".  It would be useful to be able to include a few stats alongside any game play.  I'm only at an early stage of discovering what programs I can write so start with a simple idea and then think about adding other things when they spring to mind.  I know this isn't the ideal way to plan a program as an efficient structure is important.   But I cant really plan too far ahead until I can see what is available  / possible.    I think the term "trying to run before I can walk" is appropriate for me at the moment.   :)    Thank you for your support.   It's good that people on this forum are prepared to assist and encourage beginners.

GeoffB17

Aaargh!

Just been thinking about some of the things I as saying about starting data in a file.  my mind is of course too set in the ways allowed by access to floppy disks, disk files, etc.   What I was thinking is of course FAR from so easy if you've got a cassette based system, and I suspect that OP is so placed.

You'd need to have a prog, a type of text editor, that could allow the creation of a text file which could then be saved to the tape, and then re-loaded, edited/added to, then resaved.   I don't know if there is such a thing.   Obviously, something could be written.

Geoff

DRobert

Hi I've manged to set up a simple soccer program which generates results and I can list a few teams and scores.  The one thing I am struggling with is the league table in descending order based on team points.  I have spent the last month reviewing many "bubblesort" programmes (as recommended above) and practising different procedures but due to my limited experience I cannot grasp how to take my program to the next step.  The following link was interesting and the presenter explained things in a manner that I just about got a grasp of but I cannot convert his example program to meet my needs.   https://www.youtube.com/watch?v=lfGv-KjnyHU&ab_channel=learn4free 


To give a simple example of what I would like to achieve is an AMSTRAD BASIC coding to convert the following example data into a league table based upon points attained.  If I can get my head around that I can then expand to include more teams. 


Aston Villa 2 Liverpool 4
Leeds Utd 1 Chelsea 0


In long hand the table would show as follows
1st place -  Liverpool  Played 1, won 1, drawn 0, lost 0, goals scored 4, goals conceded 2, points attained 3
2nd place - Leeds Utd Played 1, won 1, drawn 0, lost 0, goals scored 1, goals conceded 0, points attained 3
3rd place -  Chelsea    Played 1, won 0, drawn 0, lost 1, goals scored 0, goals conceded 1, points attained 0
4th place - Aston Villa Played 1, won 0, drawn 0, lost 1, goals scored 2, goals conceded 4, points attained 0

Ive written a program to print out the above league table but the amount of coding is considerable and had to type in every possible option that could occur in long hand (with GOTO's etc as opposed to getting the computer to generate the table for me). If I was to try to increase the number of teams to 20 it would take me a few years to get it all typed out which defeats the object really.    All the "bubblesort" programs just show how a series of random numbers can be sorted which looks great but doesnt help me to link numbers to team names etc.  If anyone could find a few minutes to type up an example or refer me to an online link where the code has already been done I would be grateful.  My wife is on the point of banning me from my computer as Im getting frustrated at not being able to sort what I want to do.  I repeat I am only a beginner and have not gone through all the learning processes that many of you will have done.  Trying to learn as I go.  Any help would be gratefully received. 

menegator

#12
You should sort first by wins (descending), then by (goals for - goals against)(descending) then by goals for (descending) then by name (ascending)

If you want to make it more realistic before sorting by name you should check the game(s) between the two or more teams having the same rank after the first three sorts


Have in mind that bubbleshort has O(n²) cost, depending on the set maybe you should consider another sorting method since in your case the sorting needs to be cascading.

DRobert

I've not made much progress on my "sorting" coding I'm sorry to say.   I understand the above "bubblesort" program which can sort a series of numbers but I cant see how to apply that to my needs.    Random numbers mean nothing really - its more a case of having a list of names / teams etc with associated numbers and then sorting them in order.  I tried to use a "football" example in my previous post as an example of what I need but it could apply to anything. 


If anyone could provide me with a bit of code that would help me.


Just a simple program to list say names of employees at a firm with different salaries and to sort and then print in descending order.


ie


Smith - £35000 , Jones - £40000,  Hall - £37500,  Lee - £41000


The above data may vary regularly so the program would needed to be able to take account of this and update accordingly.


If I could get this in BASIC I might be able to adapt it to my own games.   ie a soccer game where points and goals vary each game?    Im not making progress at the moment Im sorry to say.  Sorry to be a pain.  Im only a beginner.

AMSDOS

My example merely works as a Bubble sort by working out the Lowest to Highest of Incomes with Smith, Jones, Hall & Lee and making sure the Right Person is reassigned with the Right Income. All of that takes places in Line 180 which compares an income higher stored in one array v(p%) and the next position within the array v(p%+1). In order to preserve when things are shifted, variables 's' and 'w$' are used to temporary store the income (variable 's') and the name (variable 'w$'), and once the other data has been moved, the other data stored in variable 's' and variable 'w$' is put into it's new position.




100 MODE 1
110 DIM n$(4),v(4)
120 FOR p%=1 TO 4
130   READ n$(p%),v(p%)
140   LOCATE 10,p%:PRINT n$(p%):LOCATE 15,p%:PRINT v(p%)
150 NEXT p%
160 WHILE done=0
170   FOR p%=1 TO 3
180     IF v(p%)>v(p%+1) THEN s=v(p%):w$=n$(p%):v(p%)=v(p%+1):n$(p%)=n$(p%+1):v(p%+1)=s:n$(p%+1)=w$ ELSE done=1
190   NEXT p%
200 WEND
210 FOR p%=1 TO 4
220   LOCATE 10,p%+5:PRINT n$(p%):LOCATE 15,p%+5:PRINT v(p%)
230 NEXT p%
240 END
1000 DATA "Smith",35000,"Jones",40000,"Hall",37500,"Lee",41000
* Using the old Amstrad Languages :D   * with the Firmware :P
* I also like to problem solve code in BASIC :)   * And type-in Type-Ins! :D

Home Computing Weekly Programs
Popular Computing Weekly Programs
Your Computer Programs
Updated Other Program Links on Profile Page (Update April 16/15 phew!)
Programs for Turbo Pascal 3

andycadley

The trick is to realize they're really the same thing, but you're sorting an index of elements in an array by comparing the values of the relevant scores in a different array. It's difficult to find common examples of this because more modern programming languages let you put all the related fields together into records or objects.


So you need three arrays:


Teams$(n) which holds the names of all the teams.


Scores(n) which holds the corresponding score for a team.


Then Positions(n) which holds the numbers corresponding to teams in position order. I.e. if Positions (2) has a value of 5, then the teams in second place is Teams$(5) with a score of Scores(5). The positions array should be initialised with the numbers 1..n


When it comes to sorting, you sort the values in the Positions array, but you do it by instead comparing the scores in the Scores array. So if you're comparing elements in positions a and b the comparison would looks something like:


If Scores(Positions (a)) < Scores(Positions (b)) Then swap values in Positions(a) and Positions(b)



AMSDOS

Yes, I made some stuff-ups in my previous programme, though have since worked at it, so it's now a true sorting routine, it can be altered from Decending to Asending order or Visa-versa by simply adjusting the less than or to greater than signs in lines 180 and 210. Of course the size of sorting reflects the size of the Loops-1 for lines 170 and 200, so the more sorting needs to be rechecked, which is where the loop at 200 is needed.




100 MODE 1
110 DIM n$(4),v(4)
120 FOR p%=0 TO 3
130   READ n$(p%),v(p%)
140   LOCATE 10,p%+1:PRINT n$(p%):LOCATE 15,p%+1:PRINT v(p%)
150 NEXT p%
160 WHILE done=0
170   FOR p%=0 TO 2
180     IF v(p%)<v(p%+1) THEN s=v(p%):w$=n$(p%):v(p%)=v(p%+1):n$(p%)=n$(p%+1):v(p%+1)=s:n$(p%+1)=w$ ELSE done=1
190   NEXT p%
200 FOR p%=0 TO 2
210   IF v(p%)<v(p%+1) THEN done=0
220 NEXT p%
230 WEND
240 FOR p%=0 TO 3
250   LOCATE 10,p%+6:PRINT n$(p%):LOCATE 15,p%+6:PRINT v(p%)
260 NEXT p%
270 END
1000 DATA "Smith",35000,"Jones",40000,"Hall",37500,"Lee",41000
* Using the old Amstrad Languages :D   * with the Firmware :P
* I also like to problem solve code in BASIC :)   * And type-in Type-Ins! :D

Home Computing Weekly Programs
Popular Computing Weekly Programs
Your Computer Programs
Updated Other Program Links on Profile Page (Update April 16/15 phew!)
Programs for Turbo Pascal 3

DRobert

Thank you AMSDOS for a brilliant effort and for spending time helping me with my program.  :)   I had tried typing in your initial program earlier today and it worked well apart from a couple of glitches.  Great that you spent time perfecting the program which now appears to work fine.  Also thanks to "andycadley" for the explanations provided  :) .  This gives me plenty to think about and work upon.  I am learning lots along the way.  "andycadley" - your comments about there being few modern examples rings true and also reminded me that I am trying to enhamce my simple programs created in the 1990's when I was thirty odd years old.  Im now in my early 60's and finding that the brain cells arent as agile as they used to be, but I will keep plodding on.


Im am now trying to work out how I can integrate this within my soccer game program.  If the game produces new data after each set of games how do I get the computer to read this "updated data".   The DATA in the above program has been typed in by the programmer so how can I integrate the above with my own ongoing program.  Whether its employees' salaries or points achieved by a soccer team I want the DATA to update without having to "INPUT" whilst running the program or editing line 1000 everytime things change.  I realise I am light years behind you guys but I am learning a lot and hope to improve a little as time goes by.  I also appreciate that you have spent time looking at my queries.

AMSDOS

Moving from DATA to Inputting the data only just needs slight adjusting. Essentually I'm now writing a Simple Database, the main problem now is how big does it need to be. Earlier in this thread @eto posted a link to the BASIC Tutorial I typed in from ACU, which also contained a simple Database with Sorting routine, though I'll post another here:


100 MODE 2
110 DIM n$(10),v(10)
120 WHILE done=0 AND n%<>10
130   INPUT"Name:";n$(n%):INPUT"Wage:";v(n%)
140   n%=n%+1
150   IF n$(n%-1)="end" THEN n%=n%-2:done=1
160 WEND
170 done=0
180 WHILE done=0
190   FOR p%=0 TO n%-1
200     IF v(p%)<v(p%+1) THEN s=v(p%):w$=n$(p%):v(p%)=v(p%+1):n$(p%)=n$(p%+1):v(p%+1)=s:n$(p%+1)=w$ ELSE done=1
210 NEXT p%
220 FOR p%=0 TO n%-1
230   IF v(p%)<v(p%+1) THEN done=0
240 NEXT p%
250 WEND
260 FOR p%=0 TO n%
270   LOCATE 20,p%+6:PRINT n$(p%);" ";v(p%)
280 NEXT p%
290 END



This one works on the assumption there's 10 workers and once 10 people have been entered, their Salaries are sorted, however if there's less than 10 workers, the user can type-in end when Name: comes up, naturally Wage will also appear, so I just type-in 0 and the sorting takes place. The only crunch here is if only one worker is entered, followed by end, the sorting won't work and fall into an infinite loop, obviously when 'end' is entered, there's no need to display it, which is why n%=n%-2 in line 150.


It's possible to play around, so for example if 'end' is entered it'll skip asking for a wage as well:
130   INPUT"Name:";n$(n%)
140   IF n$(n%)<>"end" THEN INPUT"Wage:";v(n%):n%=n%+1 ELSE done=1
150 <delete>
170 n%=n%-1:done=0
* Using the old Amstrad Languages :D   * with the Firmware :P
* I also like to problem solve code in BASIC :)   * And type-in Type-Ins! :D

Home Computing Weekly Programs
Popular Computing Weekly Programs
Your Computer Programs
Updated Other Program Links on Profile Page (Update April 16/15 phew!)
Programs for Turbo Pascal 3

DRobert

Thank you AMSDOS for your further efforts which will help in my learning and keep me going for another month or so.  Ive have already amended your initial coding to incorporate a "20 team" English Premier League soccer table which works perfectly thank you.  I think your second program will enable me to do similar whilst INPUTting details.   My next thing is working out how to integrate my 1995 soccer program with your above coding to constantly update each time a team gets 3 points for a win, 1 point for a drawn game etc without having to physically type it in myself.  For example If say I have 4 teams in a mini league and my existing program generates the number of points next to each team how can I carry these details into the "bubblesort" as you have shown me above without me physically typing them in and more importantly updating with new points totals after each round of games played?  For instance the program will already know that Team A  has say 10 points; Team B has 18 points; Team C has 11 points and Team D has 14 points.   My existing program will simply add more points to each of these Team totals as appropriate after each round of games is complete.  Ideally if these figures can then be put into the "bubblesort mix" then the mini league table can be printed on screen as per your above two previous example codings.   Sorry to be a pain but I feel I am almost there on the direction I could go for some of my programming and mini games.  These examples are of great use to me.  Your help is greatly appreciated as are the hints and tips from all other users on this forum. 

DRobert

Hi

You guys were a great help a while back when you helped me to create a few programmes which have provided lots of enjoyment in my spare time.  Ive just got back to having another go at my Amstrad stuff and wondered if you could help me on an issue which is blocking my progress.  Apologies for being a rank amateur at this sort of thing and hopefully someone will provide a simple answer to my query.

I've create a few mini sports games including football and tennis mock ups using the randomiser facility.  Such as x=0+INT (RND*7).   I've found it quite easy to add up running totals where the increase is a fixed number on each occasion *ie  g=g+1 or g=g+3........... etc.

However I'm struggling to provide a separate running total for x where x is the random number which changes on each loop of the program.   This is on a footy game where x is the number of goals scored by a team in one game but then is likely to be different in subsequent games (or loops of the system).  What I need is a bit of code so that the running total of x goals increases agter each game.  I've tried various things like x=xg etc but I'm struggling to grasp what I need to do next.   If any kind person could type out a simple bit of code to achieve this I would be very grateful.  (my game is very simple and involves a number of goto's and gosubs to progress each stage).   

andycadley

If X is your random number, can you not just do something like:

LET x_total = x_total + x

On each pass of the loop? Or am I missing something?

DRobert

Hi Andy thanks for getting back to me. 

Yes that looks like the answer although I'm not sure how to print the running total on screen.

I inserted a line    -   print  x_total        and it came back with syntax error.   Same with   x_total+x

In fact the line you provided me has also come up with syntax error.  Am I typing something incorrectly?

I think we are close to what I need - just me poor at the programming stuff!

Appreciate your help.

andycadley

Probably aren't allowed underscores in variable names, it's been a very long time since I programmed BASIC. Try something like:

LET xtotal = xtotal + x

Instead.

DRobert

Brilliant Andy

Looks like that will work.  Just a case of me finding the correct place in the program to insert this.

Used a mini test program inserting your line and worked well.   It was so simple really but even "simple" was too much for me!  :)

Thank you so much.

Powered by SMFPacks Menu Editor Mod