Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert string to single digits and sum

I've tried for hours to find a solution to what I thought was an easy task but I failed.

I have a string consisting of 3 different characters ('I','R' & 'O') with length from 1 to 6.
E.g

IRRROO
RRORRR
IIR
RIRRO

Each character represents a number I=1,R=2,O=3
I need to convert this string to a single number, multiply with position and sum the result. E.g

IRRROO ---> (1*1)+(2*2)+(2*3)+(2*4)+(3*5)+(3*6) =52
IIR    ---> (1*1)+(1*2)+(2*3) =9

Thanks in advance for your help.

like image 612
Panos Kal. Avatar asked Apr 09 '13 05:04

Panos Kal.


1 Answers

factors have numeric equivalents. You can leverage that nicely for this example:

# original
x1 <- "IRRROO"

         # 1    2    3
levs <- c("I", "R", "O")

# split the string and convert to factors, then to numeric
x1f <- as.numeric(factor(strsplit(x1, "")[[1]], levels=levs))

# tally it up 
sum(x1f * seq_along(x1f))

Or as a nice, single-line function:

sumValue <- function(x, levs=c("I", "R", "O")) 
    sum(seq.int(nchar(x)) *  as.numeric(factor(strsplit(x, "")[[1]], levels=levs)))

sumValue("IRRROO")
# [1] 52
sumValue("IIR")
# [1] 9
like image 94
Ricardo Saporta Avatar answered Sep 24 '22 07:09

Ricardo Saporta