4
$\begingroup$

Write the function that operates as stated below:

In: "get"

Out: "2069"

In: "more"

Out: “5191716"

In: "insight"

Out: "209912231915"

Hint: First, figure out how the function works

& then implement it.

$\endgroup$
1
  • 3
    $\begingroup$ If (in=="get") return "2069" and so on $\endgroup$
    – melfnt
    Apr 21, 2020 at 21:34

3 Answers 3

7
$\begingroup$

myString.reverse().split(",").map(this.mid(index,1).toASCII()-64+index (pseudo-code)

Or, in plain English, reverse the string, convert to A1Z26 and add the position index, starting at $0$. So:

$get\to teg \to (20+0)(5+1)(7+2) \to 2069$
$more\to erom \to (5+0)(18+1)(15+2)(13+3) \to 5191716$
$insight\to thgisni \to (20+0)(8+1)(7+2)(9+3)(19+4)(14+5)(9+6) \to 209912231915$

Working JavaScript:

 function code(str) {
 arr=str.split("").reverse().map((x,i)=>str.charCodeAt(str.length-i-1)-64+i);
 return arr.join("")
 }

code("GET") "2069" code("MORE") "5191716" code("INSIGHT") "209912231915"

$\endgroup$
2
  • $\begingroup$ You could replace str.charCodeAt(...) with str.toUpperCase().charCodeAt(...) to make it work with uppercase and lowercase inputs. $\endgroup$ Apr 21, 2020 at 22:15
  • $\begingroup$ Better still just use x.charCodeAt() % 32 + i. $\endgroup$
    – Neil
    Apr 22, 2020 at 9:31
1
$\begingroup$

You can do as below:

    String alphabet = "abcdefghijklmnopqrstuvwxyz";
    String input = "insight";
    String reverse = new StringBuilder(input).reverse().toString()
    for(int i = 0; i < reverse.length(); i++) {
        System.out.print(alphabet.indexOf(reverse.charAt(i))+1+i+"");
     }
$\endgroup$
1
$\begingroup$

Python, one-liner:

''.join(str(i+1+ord(c)-ord('a')) for i,c in enumerate(s[::-1]))

or if you want to golf it, fold the +1 into the optional second argument enumerate(..., step) :

''.join(str(i+ord(c)-ord('a')) for i,c in enumerate(s[::-1],1))

or just hardwire the ASCII constants ord('a') == 97, ord('`') == 96

$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.