Was just wondering about if there was a quick way to determine # which points in a string the elements differ. I have 2 binary strings and i want to know # how many places they are not the same.
1111111100010001111011100010001011011101001100111100110001000100
0001001011001101110110000101001111111010000000010001110001000000
So i guess i need like a for loop and a counter but all i know of is the compare() and similar things but not how to go char by char
Thanks for any help
write your own implementation of a variant of KMP
public static int diff( byte [] a, byte [] b){
int diff = 0;
String byteAr1;
String byteAr2;
char A1 [];
char A2 [];
byteAr1 = hexToBin(a);
byteAr2 = hexToBin(b);
A1 = byteAr1.toCharArray();
A2 = byteAr2.toCharArray();
for( int i = 0; i < A1.length; i++){
if(A1[i] != A2[i]){
diff++;
}
}
return diff;
}
Are your strings always the same length? If so you could do something like this:
for(int i = 0; i < string1.length(); i++) {
if(string1.charAt(i) == string2.charAt(i))
//the two chars are equal
}
If the strings are different lengths that will fail though, because you'll be trying to access characters which don't exist
Convert the strings to byte arrays and use the XOR (^) operator.
Count the number of 1's.
Related
Is there a better(Faster) way to split a binary string into an Array?
My code That loops and substring every 8 characters in one element.
binary = my binary string(Huge) : "1010101011111000001111100001110110101010101"
int index = 0;
while (index < binary.length()) {
int num = binaryToInteger(binary.substring(index, Math.min(index + 8,binary.length())));
l.add( num);
temp = temp+ String.valueOf(num);
index += 8;
}
What I am trying to do is to split my binary string into pieces of 8 characters 10101010 and then get the int value of the 8 characters and will store that in arraylist witch in this case was l
My code is working but is very time consuming.. Is there a faster way of getting this done?
It's easy using regex:
binary.split("(?<=\\G.{8})");
However, it creates an array of strings. I don't get your will of creating an array of integers, since binary strings don't fit into this type (they can start with "0" and they can be really long).
I think there are mutiple options using Regex, substring, split etc available in java or Google Guavas - Splitter.fixedLength().
Splitter.fixedLength(8).split("1010101011111000001111100001110110101010101");
This Split a string, at every nth position clearly explain the performance of various functions.
It would probably faster using toCharArray:
Long time = System.currentTimeMillis();
List<Integer> l = new ArrayList<>();
int index = 0;
String binary =
"1010101011111000001111100001110110101";
char[] binaryChars = binary.toCharArray();
while (index < binaryChars.length) {
int num = 0;
for (int offset = 0; offset < Math.min(8, binary.length() - index); offset++) {
int bo = index + offset;
if (binaryChars[bo] == '1') {
num += Math.pow(2, offset + 1);
}
}
l.add(num);
index += 8;
}
System.out.println(System.currentTimeMillis() - time);
Since you want to split into groups of eight bits, I guess, you want to decode bytes rather than ints. This is easier than you might think:
String binary = "1010101011111000001111100001110110101010101";
byte[] result=new BigInteger(binary, 2).toByteArray();
Maybe you can try making a for-each loop to go through each character in the string, combine them into 8-bit values and convert into bytes. I don't know if that will be faster, just a suggestion.
for (char c : binary.toCharArray() ) { do stuff }
I'm very new to programming and I've spent some time looking for a way to do this that I can understand. I'm making a hangman game in java, it's all text based, and I've got almost the entire thing done. All I need is to replace a character array that holds the value of a random word to be replaced with dashes. So if the word was "java" I need to change that character array to "----". Since the word is chosen at random from a list, I have to find a way to use the length of the word to apply those dashes, but I'm not sure how.
Any help is appreciated!
A simple way to replace all the characters by '_' would be :
char[] charArray = {'W','O','R','D'};
Arrays.fill(charArray, '_');
I will give you an example based on what you have provided so far with java and ----:
public class Program {
public static void main(String[] args) {
String value = "java";
char[] array = value.toCharArray();
// Convert string to a char array.
for(int i = 0; i < value.length(); i++)
{
array[i] = '-';
}
// Loop over chars in the array.
for (char c : array) {
System.out.print(c);
}
}
}
OK, a few things that may be helpful in solving this task:
If you have a String you can easily get the length of that String like this:
String word = "java";
int lengthOfWord = word.length();
You can easily edit the contents of an array by accessing the individual elements:
char[] array = new char[4];
array[0] = '-';
array[1] = '_';
array[2] = '-';
array[3] = '_';
If you want to do something repeatedly and know how often you want to do that, using a for-loop is often a great idea. And you can use the counter within the loop. So for example:
int sum = 0;
for(int i = 0; i < 10; i++) {
sum += i;
}
So, combine those pieces of information and you can replace every element of that array. :-)
This question already has an answer here:
String Replace not working as I think it should [duplicate]
(1 answer)
Closed 8 years ago.
I need to cycle through each character in a string, and based on the character that it is, replace it with another character from a char array.
Basically it looks like this:
for (int k = 0; k < messageToBeEncrypted.length(); k++)
{
switch(messageToBeEncrypted.charAt(k))
{
case 'a' : messageToBeEncrypted.replace('a', cryptList[0]);
break;
case 'b' : messageToBeEncrypted.replace('b', cryptList[1]);
break;
//it keeps going for each letter of the alphabet
}
System.out.println(messageToBeEncrypted);
}
The char array cryptList is a randomly generated alphabet, "fgtaixnebqwjkzumlydrovsphc" A is to be replaced by f, b by g, and so on. The problem I'm having is that this code prints the exact same message that was inputted, so if the messageToBeEncrypted was ab, instead of fg, it prints ab. How can I fix this? And if theres a clearer more concise way to accomplish this, do tell me. I realize 26 case statements probably isn't the best way to achieve my goal.
If you want to google it the keyword is Substitution cipher.
Here a short help:
String messageToBeEncrypted = "HelloWorld".toLowerCase();
String alphabet = "fgtaixnebqwjkzumlydrovsphcab";
StringBuilder sb = new StringBuilder();
int pos;
for (int k = 0; k < messageToBeEncrypted.length(); k++)
{
pos = (messageToBeEncrypted.charAt(k) - 97);
sb.append(alphabet.charAt(pos));
}
System.out.println(sb.toString());
The number 97 is the offset in the ASCII table... My example is just for small letters, but its not that hard to complete it for every letter.
This seems about what your after (minus the brutal switch statement):
public static String substitutionCipher(String str) {
//i'm assuming that this random alphabet is exactly 26 long, each unique
char[] crypt = "fgtaixnebqwjkzumlydrovsphc".toCharArray();
char[] chars = str.toCharArray();
for(int i = 0; i < chars.length; i++){
chars[i] = crypt[((int) chars[i]) - 97];
}
return new String(chars);
}
But to answer your original question, the reason it's not working is that Strings are immutable. By calling String.replace, it's not modifying your string; that's actually returning the modified version of the string and then just disappearing since you're not storing the return value.
You'd need to say:
for (int k = 0; k < messageToBeEncrypted.length(); k++)
{
switch(messageToBeEncrypted.charAt(k))
{
case 'a' :
messageToBeEncrypted = messageToBeEncrypted.replace('a', cryptList[0]);
break;
case 'b' :
messageToBeEncrypted = messageToBeEncrypted.replace('b', cryptList[1]);
break;
//etc.
}
System.out.println(messageToBeEncrypted);
}
but the way I mentioned previously is a little gentler on memory.
I'm trying some online problems. I programmed how to solve the greatest palindrome product of 2 two-digit numbers. For example 91*99=9009. I managed to do it by using the recursive function but I wonder how can i do it using arrays like this one?
product[0]=9;
product[1]=0;
product[2]=0;
product[3]=9;
or if the computed product is 969;
product[0]=9;
product[1]=6;
product[2]=9;
Then I will output it starting from the last index to the first index then test if its equal to the original number.
EDIT:
My question is, how can i store the computed product to an array?
There's no reason to solve that Project Euler problem using arrays. But if you're fixated on it, then there is a simple algorithm to convert an array of digits into a number. Just do this:
int number = 0;
int number_2 = 0;
//going forwards:
for (int i = 0; i < array.length; i++)
{
number = number * 10 + array[i];
}
//going backwards:
for (int i = array.length - 1; i >= 0; i--)
{
number_2 = number_2 * 10 + array[i];
}
if (number == number_2)
{
//you have a palindrome
}
It's not the most efficient method, I know (#Nandkumar's is faster), but it's really really simple, that's what I was aiming for.
Create a new String from the integer product.
I won't writ you code, because it looks like an assignment, but I'll give you a hint.
Convert the int into a string first.
Characters in a string are very much like arrays, so it'll be easy to convert the string into an array.
To convert the number into an array you can try this...
Char [] product = String.valueOf("969").toCharArray();
Provide your product to String.valueOf(int), it will be converted to string and then convert it into array using String.toCharArray() like
boolean palindrome = true;
int product = 9009; // or any calculated number
char str[] = String.valueOf(product).toCharArray();
for(int i=0,j=str.length-1; i!=j ;i++,j--) {
if(str[i] == str[j]){
continue;
} else {
palindrome = false;
break;
}
}
I'm trying to convert a string filled with 16 digits into an array of ints where each index holds the digit of its respective index in the string. I'm writing a program where I need to do math on individual ints in the string, but all of the methods I've tried don't seem to work. I can't split by a character, either, because the user is inputting the number.
Here's what I have tried.
//Directly converting from char to int
//(returns different values like 49 instead of 1?)
//I also tried converting to an array of char, which worked,
//but then when I converted
//the array of char to an array of ints, it still gave me weird numbers.
for (int count = 0; count <=15; count++)
{
intArray[count] = UserInput.charAt(count);
}
//Converting the string to an int and then using division to grab each digit,
//but it throws the following error (perhaps it's too long?):
// "java.lang.NumberFormatException: For input string: "1234567890123456""
int varX = Integer.parseInt(UserInput);
int varY = 1;
for (count=0; count<=15; count++)
{
intArray[count]= (varX / varY * 10);
}
Any idea what I should do?
how about this:
for (int count = 0; count < userInput.length; ++count)
intArray[count] = userInput.charAt(count)-'0';
I think that the thing that is a bit confusing here is that ints and chars can be interpited as eachother. The int value for the character '1' is actually 49.
Here is a solution:
for (int i = 0; i < 16; i++) {
intArray[i] = Integer.valueOf(userInput.substring(i, i + 1));
}
The substring method returns a part of the string as another string, not a character, and this can be parsed to an int.
Some tips:
I changed <= 15 to < 16. This is the convetion and will tell you how many loop interations you will actually go throug (16)
I changed "count" to "i". Another convention...