Author Topic: Anyone else do what I'll call coding by substitution?  (Read 2640 times)

0 Members and 1 Guest are viewing this topic.

Offline Pete

  • Forum Resident
  • Posts: 2361
  • Cuz I sez so, varmint!
    • View Profile
Anyone else do what I'll call coding by substitution?
« on: March 06, 2019, 12:34:13 pm »
I'm reworking a string math rounding and display limit routine, and I decided to take it easy on myself, for a change, so, I started with this...

Code: QB64: [Select]
  1. IF LEN(n$) > 2 AND INSTR(n$, ".") <> 0 AND RIGHT$(n$, 1) > "4" THEN
  2.     a# = LEN(n$)
  3.     b# = INSTR(n$, ".")
  4.     c# = a# - b#
  5.     x$ = MID$(n$, 1, b# - 1) + MID$(n$, b# + 1)
  6.     y$ = RIGHT$(n$, 1)
  7.     d# = 10 - VAL(y$)
  8.     e# = VAL(x$) + d#
  9.     n2$ = LTRIM$(STR$(e#))
  10.     f# = LEN(n2$) - c#
  11.     n2$ = MID$(n2$, 1, f#) + "." + MID$(n2$, f# + 1)
  12.     DO UNTIL RIGHT$(n2$, 1) <> "0"
  13.         n2$ = MID$(n2$, 1, LEN(n2$) - 1)
  14.     LOOP
  15.     IF RIGHT$(n2$, 1) = "." THEN n2$ = MID$(n2$, 1, LEN(n2$) - 1)
  16.    n$ = n2$

That code uses a variable for just about every step. Normally, I just write long string arguments, which is the next example, without the need for doing the above. I have to admit, doing the above made it easier. By substitution, I mean I took what the variable was equal to, an substituted that part of the statement (cut and paste) wherever the variable letter occurred.

Code: QB64: [Select]
  1. IF LEN(n$) > 2 AND INSTR(n$, ".") <> 0 AND RIGHT$(n$, 1) > "4" THEN
  2.     n2$ = LTRIM$(STR$(VAL(MID$(n$, 1, INSTR(n$, ".") - 1) + MID$(n$, INSTR(n$, ".") + 1)) + 10 - VAL(RIGHT$(n$, 1))))
  3.     n2$ = MID$(n2$, 1, LEN(n2$) - (LEN(n$) - INSTR(n$, "."))) + "." + MID$(n2$, LEN(n2$) - (LEN(n$) - INSTR(n$, ".")) + 1)
  4.     DO UNTIL RIGHT$(n2$, 1) <> "0" ' Remove trailing zeros.
  5.         n2$ = MID$(n2$, 1, LEN(n2$) - 1)
  6.     LOOP
  7.     IF RIGHT$(n2$, 1) = "." THEN n2$ = MID$(n2$, 1, LEN(n2$) - 1) ' Remove a trailing decimal point.
  8.     n$ = n2$

Anyway, I'm pretty sure I haven't invented anything new in the way of coding, but I was curious if any of you guys have taken similar approach, or use other helpful methods to make complicated coding work a bit easier.

Pete
Want to learn how to write code on cave walls? https://www.tapatalk.com/groups/qbasic/qbasic-f1/

Offline bplus

  • Global Moderator
  • Forum Resident
  • Posts: 8053
  • b = b + ...
    • View Profile
Re: Anyone else do what I'll call coding by substitution?
« Reply #1 on: March 06, 2019, 06:30:59 pm »
I would go with the first code example with more descriptive variables if I wanted to explain the code to others or myself at a later date.

I would go the 2nd code example route to eliminate as many variables for most efficient processing from less variable assignments.