Heres my code that takes a string and returns an array of the ascii values for each character in the array in order. Compile error is 'array required, but java.lang.String found'
public class Q1E {
int[] stringToCodes(String characters){
int characterLength= length(characters);
int[] array=new int[characterLength];
for(int i=0;i<characterLength;i++) {
array[i] =(int) characters[i];
}
}
}
You can't use array syntax on a String, use character.charAt(i)instead. Also, you need to return the array at the end.
Java uses Unicode/UTF-16 for strings, not ASCII.
If want to restrict your method to processing characters in the ASCII range, it should throw an exception when it encounters one outside that range.
If you want a sequence of "character codes" (aka codepoints), you have to use the String.codePointAt() at method. Because String holds a counted sequences of UTF-16 code-units and there might be one or two code-units per codepoint, you only know that String.length() is an upper bound of the number of codepoints in advance.
public class Q1E {
int[] stringToCodes(String s) {
int[] codepoints = new int[s.length()]; // there might be fewer
int count = 0;
for(int cp, i = 0; i < s.length(); i += Character.charCount(cp)) {
cp = s.codePointAt(i);
// for debugging, output in Unicode stylized format
System.out.println(String.format(
cp < 0x10000 ? "U+%04X" : "U+%05X", cp));
codepoints[count++] = cp;
}
int[] array = java.util.Arrays.copyOf(codepoints, count);
return array;
}
}
Try it with this Wikipedia link on an English word:
stringToCodes("http://en.wikipedia.org/wiki/Résumé");
Your code appears to have a few bugs, it's String#length() and I would suggest you add a null check. Finally (since characters isn't an array), I think you want to use String#charAt(int)
int[] stringToCodes(String characters) {
int characterLength = 0;
if (characters != null) {
characterLength = characters.length();
}
int[] array = new int[characterLength];
for (int i = 0; i < characterLength; i++) {
array[i] = characters.charAt(i);
}
return array;
}
Of course, you could shorten it with a ternary
int characterLength = (characters != null) ? characters.length() : 0;
int[] array = new int[characterLength];
try this:
public class Test {
public static void main(String[] args) {
int []ascii=stringToCodes("abcdef");
for(int i=0;i<ascii.length;i++){
System.out.println(ascii[i]);
}
}
public static int [] stringToCodes(String characters){
int []ascii=new int[characters.length()];
for(int i=0;i<characters.length();i++){
ascii[i]=(int)characters.charAt(i);
}
return ascii;
}
}
Related
I would like to ask for advice, if there is a more efficient way to find a strings' permutation based on its alphabetical order, like my code below.
I'm working with strings long up to 16 characters, and huge amount of data, and running my program takes too much time and memory.
Basic representation of the problem
input: alphabet
output: 16752348
So in the word "alphabet" letter 'a' is the first in the alphabet, mark it index 1, then comes another 'a' in the fifth position, mark it 2, then comes 'b' in the sixth position, mark it 3 and so on..
In the code I don't use numbers as indexes, instead of, I use characters, so from value 65 of the ASCII value. (Because I use test long strings. But it doesn't change the main purpose). So the output of my program will be
input: alphabet
output: AFGEBCDH
public static String perm(String word){
char[] perm = new char[word.length()];
char[] wordArray = word.toCharArray();
char[] sortedWord = new char[word.length()];
sortedWord = word.toCharArray();
Arrays.sort(sortedWord);
for (int i=0; i<word.length(); i++){
for (int j=0; j<word.length(); j++){
if (sortedWord[i] == wordArray[j]){
perm[j] = (char)(65+i); //from A
wordArray[j] = '.';
j = word.length(); //in case, if the word has more of the tested char, we jump to the end of the cycle
}
}
}
return String.valueOf(perm);
}
public static void main (String [] args){
System.out.println(perm("alphabet"));
}
I looked at my previous solution, and it appears Arrays.sort() for an array of comparable takes considerably longer than on arrays of primitive types.
I tried a couple more approaches, and the following is the one that gave smaller time for large number of words:
public static String perm(String word){
int l = word.length();
int[] els = new int[l];
for (int i=0; i<l; i++) {
els[i] = (word.charAt(i) << 16) | i;
}
Arrays.sort(els);
char[] sb = new char[l];
for (int i=0; i<els.length; i++) {
sb[i] = (char)('A' + els[i] & 0xFFFF);
}
return String.valueOf(sb);
}
Note that the approach makes the implicit assumptions that the words only use the lower 15 bits of the UTF-16 encoding (true for words in english alphabet).
In terms of memory utilization, you have to be a bit careful about what you measure in Java. The fact that memory utilization may spike in one approach vs. another, is not necessarily a good indicator, as that memory may be garbage collected. All of the approaches here use temporary arrays/objects which are available to garbage collection after perm() is executed (except for the returned string). Now, if you care about reducing memory utilization in order to reduce garbage collection (and therefore improve performance), I suspect this last approach should give good results, although I haven't measured that.
WRT memory utilization, the program you pasted won't use much. What are you doing with the returned strings in the real code?
As far as performance goes, this should be a bit better:
import java.util.Arrays;
class El implements Comparable<El>{
char c;
int idx;
public El(char c, int idx) {
this.c = c;
this.idx = idx;
}
public int compareTo(El other) {
return Character.compare(c, other.c);
}
}
public class Perm {
public static String perm(String word){
int l = word.length();
El[] els = new El[l];
for (int i=0; i<l; i++) {
els[i] = new El(word.charAt(i), i);
}
Arrays.sort(els);
StringBuilder sb = new StringBuilder(l);
for (int i=0; i<els.length; i++) {
sb.append((char)('A' + els[i].idx));
}
return sb.toString();
}
public static void main (String [] args){
System.out.println(perm("alphabet"));
}
}
Try this:
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
public class alphabet {
public static List<CharIndexHolder> charlist = new ArrayList<CharIndexHolder>();
public static String perm(String word) {
char[] perm = new char[word.length()];
char[] wordArray = word.toCharArray();
char[] sortedWord = new char[word.length()];
sortedWord = word.toCharArray();
Arrays.sort(sortedWord);
for (int i=0; i<word.length(); i++){
for (int j=0; j<word.length(); j++){
if (sortedWord[i] == wordArray[j]){
perm[j] = (char)(65+i); //from A
wordArray[j] = '.';
j = word.length(); //in case, if the word has more of the tested char, we jump to the end of the cycle
}
}
}
return String.valueOf(perm);
}
public static String perm2(String word) {
charlist.clear();
for(int i = 0; i < word.length(); i++) {
charlist.add(new CharIndexHolder(word.charAt(i), i));
}
Collections.sort(charlist);
for(int i = 0; i < charlist.size(); i++) {
charlist.get(i).assignedindex = i;
}
char[] result = new char[word.length()];
for(int i = 0; i < result.length; i++) {
CharIndexHolder cur = charlist.get(i);
result[cur.index] =(char) (charlist.get(i).assignedindex + 65);
}
return new String(result);
}
public static void main (String [] args){
System.out.println(perm("alphabet"));
System.out.println(perm2("alphabet"));
}
}
Helper class:
public class CharIndexHolder implements Comparable<CharIndexHolder> {
public int index;
private char character;
public int assignedindex;
CharIndexHolder(Character character, int index) {
this.character = character;
this.index = index;
}
#Override
public int compareTo(CharIndexHolder o) {
if(this.character < o.character) {
return -1;
}
if(this.character > o.character) {
return 1;
}
if(this.index < o.index) {
return -1;
}
if(this.index > o.index) {
return 1;
}
return 0;
}
}
I can't think of a way to go faster than N*log(n). If you need more speed, try replacing the list with a long array, but only allocate the array once per batch (not once per call).
Hi biologist here with a little bit of coding background. my goal is to be able to input a string of characters and the code to be able to tell me how many times they occur and at what location in the string.
so ill be entering a string and i want the location and abundance of sq and tq within the string. with the location being the first character e.g njnsqjjfl sq would be located at postition 4.
This is what ive come up with so far (probably very wrong)
string S = "...";
int counter =0;
for(int i=0; i<s.length; i++){
if(s.charAt (i) == 'sq')}
counter++;})
string S = "...";
int counter =0;
for(int i=0; i<s.length; i++){
if(s.charAt (i) == 'tq')}
counter++;})
any input will help, thankyou
So , you can have multiple occurrences of "sq" and "tq" in your code, so you can have 2 arraylists to save these two separately(or one to save them together).
ArrayList<Integer>sqLocation = new ArrayList<>();
ArrayList<Integer>tqLocation = new ArrayList<>();
for(int i =0;i<s.length()-1;i++){
if(s.charAt(i)=='s' && s.charAt(i+1)=='q'){
sqLocation.add(i);
}
else if(s.charAt(i)=='t' && s.charAt(i+1)=='q'){
tqLocation.add(i);
}
}
System.out.println("No. of times sq occurs = "+sqLocation.size());
System.out.println("Locations ="+sqLocation);
System.out.println("No. of times tq occurs = "+tqLocation.size());
System.out.println("Locations ="+tqLocation);
This can be achieved using regex. Your use case is to count occurrences and position of those occurrences. The method match returns an integer list which is position and count is size of list
Exmaple code
public class RegexTest {
public static List<Integer> match(String text, String regex) {
List<Integer> matchedPos = new ArrayList<>();
Matcher m = Pattern.compile("(?=(" + regex + "))").matcher(text);
while(m.find()) {
matchedPos.add(m.start());
}
return matchedPos;
}
public static void main(String[] args) {
System.out.println(match("sadfsagsqltrtwrttqsqsqsqsqsqs", "sq"));
System.out.println(match("sadfsagsqltrtwrttqksdfngjfngjntqtqtqtqtqtq", "tq"));
}
}
what you want is a HashMap <String, List <Integer>>
this will hold, the String that you are looking for e.g. sq or tq, and a List of the positions that they are at.
You want to loop around using String.indexOf see https://docs.oracle.com/javase/7/docs/api/java/lang/String.html#indexOf(java.lang.String,%20int)
psuedocode being
String contents = "sadfsagsqltrtwrttqksdfngjfngjntqtqtqtqtqtq";
map.add (lookFor, new ArrayList ());
int index = 0;
while ((index = contents.indexOf (lookFor, index)) != -1) {
list = map.get (lookFor);
list.add (index);
}
You should use not charAt but substring to get a part of String.
int count(String s, String target) {
int counter = 0;
int tlen = target.length();
for (int i = tlen; i < s.length(); i++) {
if (s.substring(i - tlen, i).equals(target)) {
counter++;
}
}
return counter;
}
// in some method
count("...", "sq");
count("...", "tq");
I need a String array with the following attributes:
4 digits numbers
No repeating digits ("1214" is invalid)
No 0's
Is there an easier way to do this than manually type it? Like:
String[] s = {"1234","1235",1236",1237",1238",1239","1243","1245"};
Sorry for my English!
The following code will generate an array with your specifications.
public class Test {
public static void main(String[] args) {
List<String> result = new ArrayList<>();
Set<Character> set = new HashSet<>();
for (int i = 1234; i <= 9876; i++) {
set.clear();
String iAsString = Integer.toString(i);
char[] chars = iAsString.toCharArray();
boolean valid = true;
for (char c : chars) {
if (c == '0' || !set.add(c)) {
valid = false;
break;
}
}
if (valid) {
result.add(iAsString);
}
}
String[] yourStringArray = result.toArray(new String[result.size()]);
System.out.println(Arrays.toString(yourStringArray));
}
}
****edit****
Just saw that it is in Java. So use this function: String.valueOf(number) to convert integer to string if none of the digits are repeats in the loop.
Not sure what language you are doing but I am assuming no repeats not replies.
So what you can do is have a loop from 0 to 9999 and then run through all the numbers while checking if each digit has repeats if so discard number (do not store it into array).
You can convert integers to strings in many languages in their function so you can do that then store it into array.
Good luck.
Hope this helped (fastest solution from my head...there could be more efficient ones)
Try this method for creating Random number with your structure :
ArrayList<Integer> rawNumbers = new ArrayList<Integer>(Arrays.asList(1,2,3,4,5,6,7,8,9));
public String createRandomNumberSring()
{
String result = "";
ArrayList<Integer> numbers = new ArrayList<Integer>();
numbers.addAll(rawNumbers);
for(int i = 0; i < 4; i++)
{
int index = (int)(Math.random() * (numbers.size() + 1));
result += numbers.get(index).toString();
numbers.remove(index);
}
return result;
}
there. I faced a bit trouble with java programming
**Could someone give me a hint which of the method use in order to
string= "23578893762467290465" convert to array y= [2,3,5,7]....??**
I mean, that for example y[0]=2, y[1]=3, y[2]=5....
Thanks in advance
String.toCharArray()
From the official documentation:
It returns a newly allocated character array whose length is the
length of this string and whose contents are initialized to contain
the character sequence represented by this string.
Convert String to an integer array.
String string= "23578893762467290465";
int[] intArray = new int[string.length()];
for(int i = 0; i<string.length(); i++){
intArray[i] = Integer.parseInt(String.valueOf(string.charAt(i)));
}
public class StringToInt{
public int[] convert(String arg){
char[] characters = arg.toCharArray();
int[] integers = new int[arg.length()];
for ( int i = 0; i < characters.length; i++ )
integers[i] = Character.getNumericValue(characters[i]);
return integers;
}
private void prettyPrint(int[] result){
System.out.print("array: ");
for(int i : result){
System.out.print(i+" ");
}
}
public static void main(String[]args){
StringToInt converter = new StringToInt();
int[] result = converter.convert(args.length > 0?args[0]: "23578893762467290465" );
converter.prettyPrint(result);
}
}
ok, people beat me to it. But this'll work.
in essence:
Convert to char-array.
call Character.getNumericValue() for each character.
Another way may be:
int[] arr = new int[string.length()];
for(int i = 0; i<string.length(); i++){
arr[i] = Character.getNumericValue(string.charAt(i));
System.out.println(arr[i] + " ") ;
}
I have a string that I want to split with a certain delimiter
private int [] mMaxValues;
public void setMaximum(String maximum) {
mMaxValues = splitByDelimiter(maximum, ":");
}
But the splitByDelimiter method return a string array into an int array
public String[] splitByDelimiter(String list,String delimiter) {
String[] items = list.split("\\" + delimiter);
for (String s : items) {
s.trim();
}
return items;
}
What is the best way to fix this problem? I'm guessing that iterating the string array and casting them to integers isn't the best solution.
I could also create a new splitByDelimiter that returns an int array but I'm guessing there is a better solution than that..
Is this a situation where you could use generics (I don't have a lot of experience with generics)?
Thx :)
You need to convert string array to int array explicitly. Use:
public void setMaximum(String maximum) {
Strin[] array = splitByDelimiter(maximum, ":");
int i = 0;
mMaxValues = new int[array.length];
for (String value : array) {
mMaxValues[i] = Integer.parseInt(value);
i++;
}
}
Also you need to handle few cases which may cause NullPointerException :
maximum is null
array is null
NumberFormatException may be raised while parsing Integer.parseInt(value), handle it.
Loop over the string array and store them in an int array.
String input = ...;
String[] parts = input.split(':');
int[] result = new int[parts.length];
for (int n = 0; n < parts.length; ++n)
{
result[n] = Integer.parseInt(parts[n]);
}
return result