How to define a 2-Column Array A = 1, B = 2... ZZZ =? - abap

I need to create a 2 column array in ABAP so that a program can look up a record item (defined by the letters A - ZZZ) and then return the number associated with it.
For example:
A = 1
B = 2
C = 3
...
Z = 26
AA = 27
AB = 28
...
AZ =
BA =
...
BZ =
CA =
...
...
ZZZ =
Please can you suggest how I can code this.
Is there a better option than writing an array?
Thanks.

you don't need to lookup the value in a table. this can be calculated:
parameters: p_input(3) type c value 'AAA'.
data: len type i value 0,
multiplier type i value 1,
result type i value 0,
idx type i.
* how many characters are there?
len = strlen( p_input ).
idx = len.
* compute the value for every char starting at the end
* in 'ABC' the C is multiplied with 1, the B with 26 and the A with 26^2
do len times.
* p_input+idx(1) should be the actual character and we look it up in sy-abcde
search p_input+idx(1) in SY-ABCDE.
* if p_input+idx(1) was A then sy-fdpos should now be set to 0 that is s why we add 1
compute result = result + ( sy-fdpos + 1 ) * multiplier.
idx = idx - 1.
multiplier = multiplier * 26.
enddo.
write: / result.
i didn't test the program and it has pretty sure some syntax errors. but the algorithm behind it should work.

perhaps I'm misunderstanding, but don't you want something like this?
type: begin of t_lookup,
rec_key type string,
value type i,
end of t_lookup.
data: it_lookup type hashed table of t_lookup with unique key rec_key.
then once it's populated, read it back
read table it_lookup with key rec_key = [value] assigning <s>.
if sy-subrc eq 0.
" got something
else.
" didn't
endif.
unfortunately, arrays don't exist in ABAP, but a hashed table is designed for this kind of lookup (fast access, unique keys).

DATA: STR TYPE STRING, I TYPE I, J TYPE I, K TYPE I, CH TYPE C, RES
TYPE INT2, FLAG TYPE I.
PARAMETERS: S(3).
START-OF-SELECTION.
I = STRLEN( S ).
STR = S.
DO I TIMES.
I = I - 1.
CH = S.
IF CH CO '1234567890.' OR CH CN SY-ABCDE.
FLAG = 0.
EXIT.
ELSE.
FLAG = 1.
ENDIF.
SEARCH SY-ABCDE FOR CH.
J = I.
K = 1.
WHILE J > 0.
K = K * 26.
J = J - 1.
ENDWHILE.
K = K * ( SY-FDPOS + 1 ).
RES = RES + K.
REPLACE SUBSTRING CH IN S WITH ''.
ENDDO.
* RES = RES + SY-FDPOS.
IF FLAG = 0.
MESSAGE 'String is not valid.' TYPE 'S'.
ELSE.
WRITE: /, RES .
ENDIF.
Use this code after executing.

I did a similar implementation some time back.
Check this it it works for you.
DATA:
lv_char TYPE char1,
lv_len TYPE i,
lv_len_minus_1 TYPE i,
lv_partial_index1 TYPE i,
lv_partial_index2 TYPE i,
lv_number TYPE i,
result_tab TYPE match_result_tab,
lv_col_index_substr TYPE string,
lv_result TYPE i.
FIELD-SYMBOLS:
<match> LIKE LINE OF result_tab.
lv_len = strlen( iv_col_index ) .
lv_char = iv_col_index(1).
FIND FIRST OCCURRENCE OF lv_char IN co_char RESULTS result_tab.
READ TABLE result_tab ASSIGNING <match> INDEX 1.
lv_number = <match>-offset .
lv_number = lv_number + 1 .
IF lv_len EQ 1.
ev_col = ( ( 26 ** ( lv_len - 1 ) ) * lv_number ) .
ELSE.
lv_len_minus_1 = lv_len - 1.
lv_col_index_substr = iv_col_index+1(lv_len_minus_1) .
CALL METHOD get_col_index
EXPORTING
iv_col_index = lv_col_index_substr
IMPORTING
ev_col = lv_partial_index2.
lv_partial_index1 = ( ( 26 ** ( lv_len - 1 ) ) * lv_number ) + lv_partial_index2 .
ev_col = lv_partial_index1 .
ENDIF.
Here The algorithm uses a recursive logic to determine the column index in numbers.
This is not my algorithm but have adapted to be used in ABAP.
The original algorithm is used in Open Excel, cant find any links right now.

Related

Label a set of objects with (A->Z,AA->ZZ, AAA->ZZZ) in VBA

I have a set which has an unknown number of objects. I want to associate a label to each one of these objects. Instead of labeling each object with a number I want to label them with letters.
For example the first object would be labeled A the second B and so on.
When I get to Z, the next object would be labeled AA
AZ? then BA, BB, BC.
ZZ? then AAA, AAB, AAC and so on.
I'm working using Mapbasic (similar to VBA), but I can't seem to wrap my head around a dynamic solution. My solution assumes that there will be a max number of objects that the set may or may not exceed.
label = pos1 & pos2
Once pos2 reaches ASCII "Z" then pos1 will be "A" and pos2 will be "A". However, if there is another object after "ZZ" this will fail.
How do I overcome this static solution?
Basically what I needed was a Base 26 Counter. The function takes a parameter like "A" or "AAA" and determines the next letter in the sequence.
Function IncrementAlpha(ByVal alpha As String) As String
Dim N As Integer
Dim num As Integer
Dim str As String
Do While Len(alpha)
num = num * 26 + (Asc(alpha) - Asc("A") + 1)
alpha = Mid$(alpha, 2,1)
Loop
N = num + 1
Do While N > 0
str = Chr$(Asc("A") + (N - 1) Mod 26) & str
N = (N - 1) \ 26
Loop
IncrementAlpha = str
End Function
If we need to convert numbers to a "letter format" where:
1 = A
26 = Z
27 = AA
702 = ZZ
703 = AAA etc
...and it needs to be in Excel VBA, then we're in luck. Excel's columns are "numbered" the same way!
Function numToLetters(num As Integer) As String
numToLetters = Split(Cells(1, num).Address(, 0), "$")(0)
End Function
Pass this function a number between 1 and 16384 and it will return a string between A and XFD.
Edit:
I guess I misread; you're not using Excel. If you're using VBA you should still be able to do this will the help of an reference to an Excel Object Library.
This should get you going in terms of the logic. Haven't tested it completely, but you should be able to work from here.
Public Function GenerateLabel(ByVal Number As Long) As String
Const TOKENS As String = "ZABCDEFGHIJKLMNOPQRSTUVWXY"
Dim i As Long
Dim j As Long
Dim Prev As String
j = 1
Prev = ""
Do While Number > 0
i = (Number Mod 26) + 1
GenerateLabel = Prev & Mid(TOKENS, i, 1)
Number = Number - 26
If j > 0 Then Prev = Mid(TOKENS, j + 1, 1)
j = j + Abs(Number Mod 26 = 0)
Loop
End Function

Assign values to dynamic structure

Need idea on the below codes, on how to simplify. Codes below works good but is there a way I could enhance or shorten the codes making it dynamic?
TYPES: BEGIN OF lty_dates,
yesterday TYPE string,
today TYPE string,
tomorrow TYPE string,
END OF lty_dates.
DATA: it_table TYPE TABLE OF lty_dates.
DO 3 TIMES.
CASE lv_count.
WHEN 1.
it_table[ 1 ]-zyesterday = 'Result Yesterday'.
it_table[ 2 ]-zyesterday = 'Result Yesterday'.
it_table[ 3 ]-zyesterday = 'Result Yesterday'.
WHEN 2.
it_table[ 1 ]-ztoday = 'Result Today'.
it_table[ 2 ]-ztoday = 'Result today'.
it_table[ 3 ]-ztoday = 'Result Today'.
WHEN 3.
it_table[ 1 ]-ztommorrow = 'Result Tomorrow'.
it_table[ 2 ]-ztommorrow = 'Result Tomorrow'.
it_table[ 3 ]-ztommorrow = 'Result Tomorrow'.
ENDCASE.
lv_count = lv_count + 1.
ENDDO.
My idea is something like the below pseudocodes. I would not want to perform CASE multiple times specially instances if fields for it_table would reach 100 (fields).
DO 3 TIMES.
ASSIGN 'ZTODAY' TO <dynamic_fieldname>.
it_table[ 1 ]-<dynamic_fieldname> = <dynamic_result>.
it_table[ 2 ]-<dynamic_fieldname> = <dynamic_result>.
it_table[ 3 ]-<dynamic_fieldname> = <dynamic_result>.
ENDDO.
Please help or light me up on this.
You could use the command ASSIGN COMPONENT compname OF STRUCTURE structure TO <field_symbol>.
TYPES: BEGIN OF lty_dates,
yesterday TYPE string,
today TYPE string,
tomorrow TYPE string,
END OF lty_dates.
TYPES: BEGIN OF lty_result ,
fieldname TYPE fieldname,
result TYPE string,
END OF lty_result .
FIELD-SYMBOLS <data> TYPE any .
DATA: lt_table TYPE TABLE OF lty_dates,
lt_result TYPE TABLE OF lty_result.
lt_result = VALUE #( ( fieldname = 'yesterday'
result = 'Result Yesterday' )
( fieldname = 'today'
result = 'Result Today' )
( fieldname = 'tomorrow'
result = 'Result Tomorrow' ) ).
lt_table = VALUE #( ( ) ( ) ( ) ). " 3 empty lines
LOOP AT lt_table ASSIGNING FIELD-SYMBOL(<table>) .
LOOP AT lt_result ASSIGNING FIELD-SYMBOL(<result>) .
ASSIGN COMPONENT <result>-fieldname OF STRUCTURE <table> TO <data> .
<data> = <result>-result.
ENDLOOP .
ENDLOOP .
Actually, your code creates this result table:
YESTERDAY TODAY TOMORROW
Result Yesterday Result Today Result Tomorrow
Result Yesterday Result today Result Tomorrow
Result Yesterday Result Today Result Tomorrow
Why not to use macro for this? Macro can perfectly fulfill your needs:
FIELD-SYMBOLS: <fvalue> TYPE ANY.
DEFINE put_values.
ASSIGN COMPONENT &1 OF STRUCTURE &2 TO <fvalue>.
<fvalue> = &3.
END-OF-DEFINITION.
it_table = VALUE #( ( ) ( ) ( ) ).
LOOP AT it_table ASSIGNING FIELD-SYMBOL(<fs_tab>).
put_values 'yesterday' <fs_tab> 'Result Yesterday'.
put_values 'today' <fs_tab> 'Result Today'.
put_values 'tomorrow' <fs_tab> 'Result Tomorrow'.
ENDLOOP.
This will work if the number if the loop iterations are equal to lines of itab (as in your code).

Generalizing increasing number of nested loop algorithm

Sorry for the terrible title, but I have no clue on how to generalize (or simplify) my loop case here.
I have a program that iterates to a sequence of integer, for example dimension=1 to 5.
In each iteration, there will be a main loop, and inside the main loop, there will be a nested loop. The number of the nested loop will be [dimension].
For example, in dimension=1, there is a For loop. In dimension=2, there is a For loop inside a For loop. And so on.
Is there any possible way to simplify the algorithm? currently I'm manually write totally different code for each value of [dimension]. Imagine if dimension=1 to 100? I'll be dead.
Here's my piece of program (written in VB.NET)
for dimension=2
Dim result(2) As Integer
For i = 0 To 1
For j = 0 To 1
result(0)=i
result(1)=j
Next
Next
For dimension=3
Dim result(3) As Integer
For i = 0 To 1
For j = 0 To 1
For k = 0 To 1
result(0)=i
result(1)=j
result(2)=k
Next
Next
Next
For dimension=4
Dim result(4) As Integer
For i = 0 To 1
For j = 0 To 1
For k = 0 To 1
For l = 0 To 1
result(0)=i
result(1)=j
result(2)=k
result(3)=l
Next
Next
Next
Next
And so on..
Any suggestion?
Thanks!
There are plenty of solutions:
Recursion
Idk, if vb.net supports methods, but if it does, this would probably be the simplest:
void nestedLoop(int lower , int upper , int remaining_loops , int[] values)
if(remaining_loops == 0)
//process values list
else
for int i in [lower , upper)
values[remaining_loops] = i
nestedLoop(lower , upper , remaining_loops - 1)
Integer Transformation
In theory, a number can be represented by any radix:
d_i * radix ^ i + d_i-1 * radix ^ (i - 1) ... + d_0 * radix ^ 0
Consider each digit the value of one of the nested loops:
for int i in [0 , max)
for int j in [0 , max)
for int k in [0 , max)
...
Could be represented by a 3-digit number with radix max, where d_0 = i, d_1 = j, etc.. Basically how each digit is mapped to one of the values can be arbitrary and will only affect the order of the output.
void nestedLoops(int upper , int dimension)
for int i in [0 , pow(upper , dimension))
int[] values
int digit_sub = 1
int tmp = i
for int j in [0 , dimension)
values[j] = tmp % dimension
tmp /= dimension
//all values of the loops are now in values
//process them here
There would be a few other options aswell, but these are the most common.
Please do note that when you do
Dim result(2) As Integer
You are actually declaring an array of 3 elements see this question for why. It's a subtle difference in VB.NET
That being said, I'll assume that you meant to declare an array of only 2 elements. If this is the case then you could build and call a recursive function like this
LoopOver(result)
Sub LoopOver(ByRef array() As Integer, ByVal Optional level As Integer = 0)
If array.Length = level Then
Return
Else
array(level) = 1
LoopOver(array, level + 1)
End If
End Sub
This recursive function will call itself (i.e., it will loop) for as many times as the array's size.

Given value p, return last element of sequence < p - Fortran

I have a sequence of numbers as follows:
1 , 1, 5, 13, 41, 121, 365, ....
The first two values are:
N(1) = 1 and N(2) = 1
As from 3rd value, N(i) = 2*N(i-1) + 3*N(i-2)
The issue I am facing with is: If I give an argument of p, it should return me the last values of the sequence < p (Using fortran77).
For instance, if p = 90, it should return the value 41.
a = 1
b = 1
while b < p:
c = 2 * b + 3 * a
a = b
b = c
return a
The Fortran equivalent is:
function fct(p) result(a)
integer, intent(in) :: p
integer :: a, b, c
a = 1
b = 1
do while (b < p)
c = 2 * b + 3 * a
a = b
b = c
enddo
end function
program test
integer :: fct
external fct
print *,fct(90)
end program
Assuming you already have the sequence in a variable lst, and p set,
max(filter(lambda x:x<=p, lst))
def get_last_element(p):
n1 = 1
n2 = 1
while True:
if n2 > p:
return n1
n1, n2 = n2, 2*n2 + 3 * n1
print(get_last_element(90))
I wrote a piece of code in Fortran 2003. I defined a type which has memory for two last parts of the sequence.The procedure is a recursive function. The type can be used standalone to get n-th part of the sequence or efficiently placed in a loop to find parts in a row (not necessarily beginning at 1) as it has memory of previous parts. (compiler: gfortran 4.8).
The type is defined in mymod.f90 file as
module mymod
implicit none
type seq_t
integer :: saved_i = 0, saved_val_i = 0, saved_val_i_1 = 0
contains
procedure :: getpart => getpart_seq
end type
contains
recursive function getpart_seq(this,i) result(r)
class(seq_t) :: this
integer, intent(in) :: i
integer :: r,r_1,r_2
if (i.eq.1.or.i.eq.2) then
r = 1
elseif(i.eq.this%saved_i) then
r = this%saved_val_i
elseif(i.eq.this%saved_i-1) then
r = this%saved_val_i_1
else
r_1 = this%getpart(i-1)
r_2 = this%getpart(i-2)
r = 2*r_1 + 3*r_2
this%saved_val_i_1 = r_1
end if
this%saved_i = i
this%saved_val_i = r
end function getpart_seq
end module mymod
The main program for the requested case is
program main
use mymod
implicit none
type (seq_t) :: seq
integer :: i,p,tmp_new,tmp_old,ans
! Set the threshold here
p = 90
! loop over parts of the sequence
i = 0
do
i = i + 1
tmp_new = seq%getpart(i)
print*,tmp_new
if (tmp_new>p) then
ans = tmp_old
exit
end if
tmp_old = tmp_new
end do
print*,"The last part of sequence less then",p," is equal to",ans
end program
The outcome is
1
1
5
13
41
121
The last part of sequence less then 90 is equal to 41.

How to read the position value given the cost center

I want to read the position using this FM HRWPC_RPT_COSTCENTER_EVALPATH where the cost center is given.
There are 3 result tables. from which table I can read the position value ?
here how I call the FM:
DATA i_hrrootob TYPE TABLE OF hrrootob.
DATA w_hrrootob LIKE LINE OF i_hrrootob.
DATA i_object_tab TYPE TABLE OF objec.
DATA w_object_tab LIKE LINE OF i_object_tab.
data i_STRUC TYPE TABLE OF STRUC.
w_hrrootob-otype = 'K'.
w_hrrootob-objid = w_orgdata-costcenter_key-costcenter.
APPEND w_hrrootob TO i_hrrootob.
CALL FUNCTION 'HRWPC_RPT_COSTCENTER_EVALPATH'
EXPORTING
depth = 0
evpath = 'KOSTDIUP'
* PLVAR = 01
* BEGDA = SY-DATUM
* ENDDA = SY-DATUM
* LEVEL = 1
TABLES
root_objects = i_hrrootob
result_objec = i_object_tab
result_struc = i_STRUC
EXCEPTIONS
NO_OBJECTS_FOUND = 1
OTHERS = 2
.
I got it by myself.
The result table result_objec has the value in the field stext, where the obtype ='S'