How to resolve the algorithm A+B step by step in the sed programming language

Published on 12 May 2024 09:40 PM

How to resolve the algorithm A+B step by step in the sed programming language

Table of Contents

Problem Statement

A+B   ─── a classic problem in programming contests,   it's given so contestants can gain familiarity with the online judging system being used.

Given two integers,   A and B. Their sum needs to be calculated.

Two integers are written in the input stream, separated by space(s):

The required output is one integer:   the sum of A and B.

Let's start with the solution:

Step by Step solution about How to resolve the algorithm A+B step by step in the sed programming language

Source code in the sed programming language

: Loop
# All done
/^-*00* /s///
/ -*00*$/s///
t

# Negative Check
/^\(-*\)[0-9].* \1[0-9]/!b Negative

# Create magic lookup table
s/\(.[0-9]*\) \(.[0-9]*\)/\1;987654321000009999000999009909 \2;012345678999990000999000990090/
s/ \(-\)*\(9*;\)/ \10\2/
# Decrement 1st number
s/\([^0]\)\(0*\);[^0]*\1\(.\).*\2\(9*\).* \(.*\)/\3\4 \5/
# Increment 2nd
s/\([^9]\)\(9*\);[^9]*\1\(.\).*\2\(0*\).*/\3\4/
t Loop

: Negative
# Create magic lookup table
s/\(.[0-9]*\) \(.[0-9]*\)/\1;987654321000009999000999009909 \2;987654321000009999000999009909/
# Decrement 1st number
s/\([^0]\)\(0*\);[^0]*\1\(.\).*\2\(9*\).* \(.*\)/\3\4 \5/
# Decrement 2nd
s/\([^0]\)\(0*\);[^0]*\1\(.\).*\2\(9*\).*/\3\4/
t Loop

#!/bin/sed -f

# Add a marker in front of each digit, for tracking tens, hundreds, etc.
s/[0-9]/<&/g
# Convert numbers to, in essence, tally marks
s/0//g; s/1/|/g; s/2/||/g; s/3/|||/g; s/4/||||/g; s/5/|||||/g
s/6/||||||/g; s/7/|||||||/g; s/8/||||||||/g; s/9/|||||||||/g

# Multiply by ten for each digit from the back they were.
:tens 
s/|
t tens

# We don't want the digit markers any more
s/

# Negative minus negative is the negation of their absolute values.
s/^-\(|*\) *-/-\1/
# Negative plus positive equals positive plus negative, and we want the negative at the back.
s/^-\(|*\) \+\(|*\)$/\2-\1/
# Get rid of any space between the numbers 
s/ //g

# A tally on each side can be canceled.
:minus
s/|-|/-/
t minus
s/-$//

# Convert back to digits
:back
s/||||||||||/
s/<\([0-9]*\)$/<0\1/g
s/|||||||||/9/g;
s/|||||||||/9/g; s/||||||||/8/g; s/|||||||/7/g; s/||||||/6/g;
s/|||||/5/g; s/||||/4/g; s/|||/3/g; s/||/2/g; s/|/1/g;
s/
t back
s/^$/0/

  

You may also check:How to resolve the algorithm Convex hull step by step in the Java programming language
You may also check:How to resolve the algorithm Find common directory path step by step in the HicEst programming language
You may also check:How to resolve the algorithm Longest common subsequence step by step in the Raku programming language
You may also check:How to resolve the algorithm Calkin-Wilf sequence step by step in the Prolog programming language
You may also check:How to resolve the algorithm Greyscale bars/Display step by step in the zkl programming language