Skip to main content
Known Participant
Jan 31, 2025 3:01 PM UTC
Solved

Reverse a String without using reverse function

I'm unable to find where the mistake is in below code Reverse a string without reverse function: 

a!localVariables(
  local!result: ri!result,
  local!index: if(
    a!isNullOrEmpty(ri!index),
    length(ri!Input),
    ri!index
  ),
  if(
    ri!index < 1,
   ri!result,
    rule!T_Reversestring(
      ri!Input,
      local!index - 1,
      concat(
        local!result,
        index(ri!Input, local!index)
      )
    )
  )


stefanhelzle0001
Brainy
Jan 31, 2025 3:11 PM UTC

No recursion required

ri!text[len(ri!text) - enumerate(len(ri!text))]

3 replies

stefanhelzle0001
Brainy
Jan 31, 2025 3:11 PM UTC

No recursion required

ri!text[len(ri!text) - enumerate(len(ri!text))]

Known Participant
Jan 31, 2025 3:18 PM UTC

Thanks, I got to learn new way of problem solving

mikes0011
Brainy
Jan 31, 2025 3:19 PM UTC

Stefan's elegant tiny answer got me thinking about what the "elegant but somewhat more verbose" answer might be.  Once again we can rely on a!forEach() and the dataSubset sort.  The advantage with this approach is it could potentially handle use cases with a little more nuance if needed.

a!localVariables(
  local!sortMap: a!forEach(
    enumerate(len(ri!text))+1,
    
    a!map(
      index: fv!item,
      currentLetter: ri!text[fv!item]
    )
  ),
  
  local!sortedSet: todatasubset(
    arrayToPage: local!sortMap,
    pagingConfiguration: a!pagingInfo(1, -1, a!sortInfo(field: "index", ascending: false()))
  ).data,
  
  concat(local!sortedSet.currentLetter)
)

The Expression Guru