-1

what I am trying to do is encode numbers in a string into numbers acording to the alphabet an leave the numbers still. so "abc123" would be "123123". Found the solution in javascript but cannot seem to fit into java. any help would be great, thanks.

The java function would be something like

import java.util.*; 
import java.io.*;

class Main {

  public static String NumberEncoding(String str) {
    ***call javascript function or translate it into java
  }

  public static void main (String[] args) {  
    // keep this function call here     
    Scanner s = new Scanner(System.in);
    System.out.print(NumberEncoding(s.nextLine())); 
  }

}

The jasvascript function is

function NumberEncoding(str) { 
str = str.toLowerCase();
var obj = {};
var alpha = "abcdefghijklmnopqrstuvwxyz";
var result = "";
for (var i = 1; i <= alpha.length; i++) {
    obj[alpha[i-1]] = i;
}

for (var j = 0; j < str.length; j++) {
  if (str[j].match(/[a-z]/)) {
    result += obj[str[j]];
  } else {
    result += str[j]; 
  }
}
return result;
}
jvargas
  • 713
  • 1
  • 5
  • 13
  • thanks for the reply. I edited the question. any help coding it is apreciated – jvargas Oct 23 '19 at 22:21
  • 1
    Ah, I misunderstood. I thought you were trying to translate the function into java, not call it from java. [Call external javascript functions from java code](https://stackoverflow.com/questions/22856279/call-external-javascript-functions-from-java-code) has some good examples of invoking javascript stored as a string, and the answers talk about how to invoke scripts stored in a file. Hope that helps you. – azurefrog Oct 23 '19 at 22:26
  • you understood right, I am trying to translate it to java. altought if I can call javascript from java an make ir work, it would be ok too – jvargas Oct 23 '19 at 22:28

3 Answers3

1

Step one, create a variable to accumulate the String result; I would use a StringBuilder. Step two, iterate the input String one character at a time. Step three, convert that character to lower-case. Step four, check that the character is not a digit. Step five, if the character is a digit pass it through unchanged otherwise the value is easy to determine because Java characters are an integral type (e.g. 'a' + 1 = 'b' and 'b' - 1 = 'a'). Step six, return the result as a String. Finally, Java naming convention is camel case (starting with a lower case letter). Like,

public static String encodeNumber(String str) {
    StringBuilder result = new StringBuilder();
    for (int j = 0; j < str.length(); j++) {
        char c = Character.toLowerCase(str.charAt(j));
        if (c < 'a' || c > 'z') {
            result.append(c);
        } else {
            result.append(1 + c - 'a');
        }
    }
    return result.toString();
}

But, if you really wanted to, you can indeed directly call the JavaScript function from Java using Nashorn. Like,

String f = "function NumberEncoding(str) { str = str.toLowerCase();\n" 
        + "var obj = {};\n"
        + "var alpha = \"abcdefghijklmnopqrstuvwxyz\";\n" 
        + "var result = \"\";\n"
        + "for (var i = 1; i <= alpha.length; i++) {\n" 
        + "    obj[alpha[i-1]] = i;\n" + "}\n" + "\n"
        + "for (var j = 0; j < str.length; j++) {\n" 
        + "  if (str[j].match(/[a-z]/)) {\n"
        + "    result += obj[str[j]];\n" 
        + "  } else {\n" + "    result += str[j];" + "  }\n" + "}\n"
        + "return result;\n" + "}";
ScriptEngine se = new ScriptEngineManager().getEngineByName("js");
try {
    se.eval(f);
    Invocable invocable = (Invocable) se;
    Object result = invocable.invokeFunction("NumberEncoding", "zabc123");
    System.out.println(result);
} catch (Exception e) {
    e.printStackTrace();
}

For the same result.

Elliott Frisch
  • 198,278
  • 20
  • 158
  • 249
0

Steps to solve it can be

  1. Fill up an int[] of size, 26 (number of alphabets) with the values 1 to 26, corresponding to the position of letters in the alphabets.
  2. Traverse through all characters of the input string and append its position from the int[] to a StringBuilder. If the character is not an alphabet, append it as it is.

Demo:

public class Main {
    public static void main(String[] args) {
        System.out.println(numberEncoding("abc123"));// Expected: 123123
    }

    static String numberEncoding(String str) {
        str = str.toLowerCase();
        String alpha = "abcdefghijklmnopqrstuvwxyz";
        int[] obj = new int[alpha.length()];
        StringBuilder result = new StringBuilder();
        for (int i = 1; i <= obj.length; i++) {
            obj[i - 1] = i;
        }

        for (int j = 0; j < str.length(); j++) {
            if (str.charAt(j) >= 'a' && str.charAt(j) <= 'z') {
                result.append(String.valueOf(obj[j]));
            } else {
                result.append(str.charAt(j));
            }
        }
        return result.toString();
    }
}

Output:

123123
Arvind Kumar Avinash
  • 71,965
  • 6
  • 74
  • 110
0

One way to do it is to use StringBuilder.

      List<String> strings = Arrays.asList("abc123", "e2f3g4");
      for (String s : strings) {
         StringBuilder sb = new StringBuilder(s);
         for (int i = 0; i < sb.length(); i++) {
            char c = sb.charAt(i);
            if (Character.isAlphabetic(c)) {
               sb.replace(i, i + 1, Integer.toString(c - 'a' + 1));
            }
         }
         System.out.println(sb.toString());
      }

And the there's the Stream version.

      List<String> strings = Arrays.asList("123abc", "e1f2g3", "xyz123");

      List<String> converted = strings.stream().map(str -> str.chars().map(
            chr -> Character.isAlphabetic(chr) ? chr - 'a' + 1
                  : chr - '0').mapToObj(String::valueOf).collect(
                        Collectors.joining())).collect(Collectors.toList());

      System.out.println(converted);
WJS
  • 36,363
  • 4
  • 24
  • 39