Binary addition of Strings - java

I need to combine an array of strings as below ( so as each character in the result string is a bitwise & of the characters in the input string)
String a = "10110001"
String b = "01101101"
String c = "10101011"
String result = "00100001"
Solution I came up with:
long resultLong = 0;
for( String a : inputs )
{
resultLong = resultLong & Long.parseLong( a ,2);
}
String result = Long.toBinaryString( resultLong );
The number of characters in the input string could be very long, and the above solution wouldn't work (NumberFormatException) . I couldn't get my head around how to implement this, what would be the cleanest way ?

If Long is not enough for your use case then you can use BigInteger
BigInteger(String val, int radix);
Which takes a String and radix as the arguments.
BigInteger result = new BigInteger(inputs[0], 2);
for (int i = 1; i < inputs.length; i++) {
result = result.and(new BigInteger(inputs[i], 2));
}
String resultStr = result.toString(2);

Here's your algorithm. This will work for any number of Strings provided that all the Strings are of same length:
public static void main(String[] args) {
String a = "10110001";
String b = "01101101";
String c = "10101011";
String arr[] = new String[]{a, b, c};
String finalString = "";
for (int i = 0; i < arr[0].length(); i++) {
int temp = Integer.parseInt("" + arr[0].charAt(i));
for (int j = 1; j < arr.length; j++) {
temp = temp & Integer.parseInt("" + arr[j].charAt(i));
}
finalString += temp;
}
System.out.println(finalString);
}
O/P
00100001

Related

Converting a string to a long via ASCII conversion

As the title suggestions, Im trying to convert a string into a unique long by converting each char to ascii.
public class MyClass {
public long AsciiFromString(String inString)
String tempString = "";
for (int i = 0; i < inString.length(); i++) {
char c = inString.charAt(i);
String charAsASCIIString = Integer.toString((int) c);
tempString = tempString + charAsASCIIString;
}
return Long.parseLong(tempString);
}
This method throws a number format error when I pass in a string
This works just fine. But if the computed string is > Long.MAX_VALUE you will get a number format exception. You also need a catch block with your try block.
long v = AsciiFromString("thisisa");
System.out.println(v);
prints
116104105115105115
Your method
public static long AsciiFromString(String inString) {
String tempString = "";
for (int i = 0; i < inString.length(); i++) {
char c = inString.charAt(i);
String charAsASCIIString = Integer.toString((int) c);
tempString = tempString + charAsASCIIString;
}
return Long.parseLong(tempString);
}

How to check if character at current index in for loop is a specific character (e.g. the letter A, the number 2, etc)?

I'm building a simple program in Java that finds letters in strings and replaces them with a number, but I'm having trouble finding a method that will allow me to check for the exact specific character. There are plenty for digits and letters in general.
As my for loop stands now, it just replaces the letter everywhere, irregardless of whether it is within the range specified by start and end.
Any help would be appreciated.
String str = "A.A.A.A.A.A.A.A";
int start = 3;
int end = 9;
for (int i = start; i < end; i++) {
if (Character.isLetter(str.charAt(i)) {
str = str.replaceAll("A", "9");
return str;
Expected Output:
A.A.9.9.9.A.A.A
Actual Output:
9.9.9.9.9.9.9.9
In your code, you have
str = str.replaceAll("A", "9");
This will replace all the occurrences of A to 9
Instead of your approach, you should
1.Convert the string to a char array
char[] charArray = str.toCharArray();
2.Then replace each occurrence of character with a number
if (Character.isLetter(charArray[i])){
//Character Found
charArray[i] = '9';
}
3. Convert it back to string using
str = String.valueOf(charArray);
Modified Code:
String str = "A.A.A.A.A.A.A.A";
int start = 3;
int end = 9;
//Converting String to char array
char[] charArray = str.toCharArray();
for (int i = start; i < end; i++) {
if (Character.isLetter(charArray[i])){
//Character Found
charArray[i] = '9';
}
}
//Converting Back to String
str = String.valueOf(charArray);
System.out.println(charArray);
System.out.println(str);
Compare for character equality and then use string builder to replace the specified character
//Use of StringBuffer preferred over String as String are immutable
StringBuilder sb = new StringBuilder(str);
// -1 to start as index start from 0
for (int i = start-1; i < end; i++) {
char currentChar = currentString.charAt(i);
if (currentChar == "A") {
sb.setCharAt(i, '9');
}
}
return sb.toString();
I'd do it that way. Cut out the string to isolate the part you want to act on, do your replace ans stitch it all back together :
String str = "A.A.A.A.A.A.A.A";
int startIndex = 3;
int endIndex = 9;
String beginning = str.substring(0, startIndex);
String middle = str.substring(startIndex, endIndex);
String end = str.substring(endIndex);
middle = middle.replaceAll("A", "9");
String result = beginning + middle + end;
System.out.println(result);
Prints out :
A.A.9.9.9.A.A.A
EDIT:
As suggested in the comments, you could do it in one line
String str = "A.A.A.A.A.A.A.A";
int startIndex = 3;
int endIndex = 9;
String result =
str.substring(0, startIndex) +
str.substring(startIndex, endIndex).replaceAll("A", "9") +
str.substring(endIndex);
Here is an example using substrings to let you choose what portion of the string you want to test
int start = 3;
int end = 9;
String str = "A.A.A.A.A.A.A.A";
String startStr = str.substring(0,start);
String endStr = str.substring(end);
String newStr="";
char temp=' ';
for (int i = start; i < end; i++) {
temp = str.charAt(i);
if (temp=='A')
newStr+="9";
else
newStr += temp;
}
return(startStr + newStr + endStr);
You are replacing all the match found in the string and not specifying the index that needs to be replaced.
Use the StringBuffer replace method like below:
public static void main(String[] args) {
String str = "AAAAAAAA";
int start = 3;
int end = 9;
str = replaceBetweenIndexes(str, start, end, "9"); // AAA999AA
str = replaceBetweenIndexes("ABCD6EFG", start, end, "3"); // ABC363FG
}
public static String replaceBetweenIndexes(String str, int start, int end, String replaceWith) {
StringBuffer strBuf = new StringBuffer(str);
for (int i = start; i < end; i++) {
if (Character.isLetter(strBuf.charAt(i)) {
strBuf.replace(i, i+1, replaceWith);
}
}
return strBuf.toString();
}

How to generate string mask with various numbers of symbols?

For example:
I have a string mask with length = 5 symbols and I have a value with length = 3 symbols.
All combinations are:
val__, _val_, __val
another example for mask length = 3, value length = 2:
xx_, _xx
How to generate these masks programmatically?
For example in method with following signature:
String[] generateMasks(int maskLength, String val);
My attempts:
private ArrayList<String> maskGenerator2(int from, char[] value) {
ArrayList<String> result = new ArrayList<String>();
//initial position
char[] firstArray = new char[from];
for (int i=0; i<from; i++) {
if (i < value.length) firstArray[i] = value[i];
else firstArray[i] = '_';
}
result.add(String.valueOf(firstArray));
System.out.println(firstArray);
//move value
int k = 0;
while (k < from - value.length) {
char last = firstArray[from - 1];
for (int i = from - 1; i > 0; i--) {
firstArray[i] = firstArray[i - 1];
}
firstArray[0] = last;
result.add(String.valueOf(firstArray));
System.out.println(firstArray);
k++;
}
return result;
}
Maybe are there more elegant solutions for this?
Create a String consisting of repeated mask symbols to required length .. see Simple way to repeat a String in java
Use StringBuilder to insert the input string at each possible point.
Example
public static void main(String[] args) throws Exception {
System.out.println(createMask(5, "val"));
System.out.println(createMask(3, "xx"));
}
private static List<String> createMask(int length, String value) {
List<String> list = new ArrayList<String>();
String base = new String(new char[length]).replace("\0", "_");
for (int offset = 0; offset <= length - value.length(); offset++) {
StringBuilder buffer = new StringBuilder(base);
buffer.replace(offset, offset + value.length(), value);
list.add(buffer.toString());
}
return list;
}
Output
[val__, _val_, __val]
[xx_, _xx]

Cut off last half of String

I need to cut off half of a user-entered string. I've tried this and it didn't work:
Scanner sc = new Scanner(System.in);
String nameOne = sc.nextLine();
chars[] oneChars = new char[nameOne.length];
double oneLength = oneChars.length / 2;
Math.round(oneLength);
int oneLen = (int)oneLength;
String nameOneFinal = "";
for(int i = 0; i == oneLen--; i++) {
oneChars[i] = oneChars[oneLen];
nameOneFinal = nameOneFinal + oneChars[i];
}
final int mid = nameOne.length() / 2;
String[] parts = {
nameOne.substring(0, mid), // 1st part
nameOne.substring(mid), // 2nd part
};
using substring method ... you can do it
Ex:
public String extraEnd(String str) {
String s = str.substring(str.length()/2);//it will have the last half of string
return s ;
}
Use SubString method to get this
String str = "CutThisBytwo";
int len = str.length();
String firstHalfStr = str.substring(0, len/2);
String secondHalfStr = str.substring(len/2,len );
System.out.println(firstHalfStr);
System.out.println(secondHalfStr);
The easy way: using String.substring(int index1, int index2)
The hard way:
String new = "";
for(int i = 0; (i < old.length() - 1) / 2; i++){
new += old.charAt(i);
}
If it's for a homework, the hard way might get you brownie points, but if not just stick to the easy way.

In Java how do you convert a decimal number to base 36?

If I have a decimal number, how do I convert it to base 36 in Java?
Given a number i, use Integer.toString(i, 36).
See the documentation for Integer.toString
http://docs.oracle.com/javase/7/docs/api/java/lang/Integer.html#toString(int,%20int)
toString
public static String toString(int i, int radix)
....
The following ASCII characters are used as digits:
0123456789abcdefghijklmnopqrstuvwxyz
What is radix? You're in luck for Base 36 (and it makes sense)
http://docs.oracle.com/javase/7/docs/api/java/lang/Character.html#MAX_RADIX
public static final int MAX_RADIX 36
The following can work for any base, not just 36. Simply replace the String contents of code.
Encode:
int num = 586403532;
String code = "0123456789abcdefghijklmnopqrstuvwxyz";
String text = "";
int j = (int)Math.ceil(Math.log(num)/Math.log(code.length()));
for(int i = 0; i < j; i++){
//i goes to log base code.length() of num (using change of base formula)
text += code.charAt(num%code.length());
num /= code.length();
}
Decode:
String text = "0vn4p9";
String code = "0123456789abcdefghijklmnopqrstuvwxyz";
int num = 0;
int j = text.length();
for(int i = 0; i < j; i++){
num += code.indexOf(text.charAt(0))*Math.pow(code.length(), i);
text = text.substring(1);
}
First you have to convert your number it into the internal number format of Java (which happens to be 2-based, but this does not really matter here), for example by Integer.parseInt() (if your number is an integer less than 2^31). Then you can convert it from int to the desired output format. The method Integer.toString(i, 36) does this by using 0123456789abcdefghijklmnopqrstuvwxyz as digits (the decimal digits 0-9 and lower case english letters in alphabetic order). If you want some other digits, you can either convert the result by replacing the "digits" (for example toUpperCase), or do the conversion yourself - it is no magic, simply a loop of taking the remainder modulo 36 and dividing by 36 (with a lookup of the right digit).
If your number is longer than what int offers you may want to use long (with Long) or BigInteger instead, they have similar radix-converters.
If your number has "digits after the point", it is a bit more difficult, as most (finite) base-X-numbers are not exactly representable as (finite) base-Y-numbers if (a power of) Y is not a multiple of X.
This code works:
public class Convert {
public static void main(String[] args) {
int num= 2147483647;
String text="ABCD1";
System.out.println("num: " + num + "=>" + base10ToBase36(num));
System.out.println("text: " +text + "=>" + base36ToBase10(text));
}
private static String codeBase36 = "0123456789abcdefghijklmnopqrstuvwxyz";
//"0123456789 abcdefghij klmnopqrst uvwxyz"
//"0123456789 0123456789 0123456789 012345"
private static String max36=base10ToBase36(Integer.MAX_VALUE);
public static String base10ToBase36(int inNum) {
if(inNum<0) {
throw new NumberFormatException("Value "+inNum +" to small");
}
int num = inNum;
String text = "";
int j = (int)Math.ceil(Math.log(num)/Math.log(codeBase36.length()));
for(int i = 0; i < j; i++){
text = codeBase36.charAt(num%codeBase36.length())+text;
num /= codeBase36.length();
}
return text;
}
public static int base36ToBase10(String in) {
String text = in.toLowerCase();
if(text.compareToIgnoreCase(max36)>0) {
throw new NumberFormatException("Value "+text+" to big");
}
if(!text.replaceAll("(\\W)","").equalsIgnoreCase(text)){
throw new NumberFormatException("Value "+text+" false format");
}
int num=0;
int j = text.length();
for(int i = 0; i < j; i++){
num += codeBase36.indexOf(text.charAt(text.length()-1))*Math.pow(codeBase36.length(), i);
text = text.substring(0,text.length()-1);
}
return num;
}
}
If you dont want to use Integer.toString(Num , base) , for instance, in my case which I needed a 64 bit long variable, you can use the following code:
Using Lists in JAVA facilitates this conversion
long toBeConverted=10000; // example, Initialized by 10000
List<Character> charArray = new ArrayList<Character>();
List<Character> charArrayFinal = new ArrayList<Character>();
int length=10; //Length of the output string
long base = 36;
while(toBeConverted!=0)
{
long rem = toBeConverted%base;
long quotient = toBeConverted/base;
if(rem<10)
rem+=48;
else
rem+=55;
charArray.add((char)rem);
toBeConverted=quotient;
}
// make the array in the reverse order
for(int i=length-1;i>=0;--i){
if(i>=charArray.size()){
charArrayFinal.add((char) 48); // sends 0 to fix the length of the output List
} else {
charArrayFinal.add(charArray.get(i));
}
}
Example:
(278197)36=5YNP
Maybe I'm late to the party, but this is the solution I was using for getting Calc/Excel cell names by their index:
public static void main(final String[] args) {
final String base = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
System.out.println(toCustomBase(0, base));
System.out.println(toCustomBase(2, base));
System.out.println(toCustomBase(25, base));
System.out.println(toCustomBase(26, base));
System.out.println(toCustomBase(51, base));
System.out.println(toCustomBase(52, base));
System.out.println(toCustomBase(520, base));
}
public static String toCustomBase(final int num, final String base) {
final int baseSize = base.length();
if(num < baseSize) {
return String.valueOf(base.charAt(num));
}
else {
return toCustomBase(num / baseSize - 1, base) + base.charAt(num % baseSize);
}
}
Results:
A
C
Z
AA
AZ
BA
TA
Basically the solution accepts any custom radix. The idea was commandeered from here.
Not sure if the above answers did help but noting 'decimal' and 'to base36' I assume you want to convert a numeric value to base36. And as long as the Long value of the raw figure is within (0 - Long.MAX_VALUE):
String someNumericString = "9223372036854";
Long l = Long.valueOf(someNumericString);
String bases36 = Long.toString(l, 36);
System.out.println("base36 value: "+bases36);
output: 39p5pkj5i
Here is a method to convert base 10 to any given base.
public char[] base10Converter(int number, int finalBase) {
int quo;
int rem;
char[] res = new char[1];
do {
rem = number % finalBase;
quo = number / finalBase;
res = Arrays.copyOf(res, res.length + 1);
if (rem < 10) {
//Converting ints using ASCII values
rem += 48;
res[res.length - 1] = (char) rem;
} else {
//Convert int > 9 to A, B, C..
rem += 55;
res[res.length - 1] = (char) rem;
}
number /= finalBase;
} while (quo != 0);
//Reverse array
char[] temp = new char[res.length];
for (int i = res.length - 1, j = 0; i > 0; i--) {
temp[j++] = res[i];
}
return temp;
}
I got this code from this website in JavaScript, and this is my version in java:
public static String customBase (int N, String base) {
int radix = base.length();
String returns = "";
int Q = (int) Math.floor(Math.abs(N));
int R = 0;
while (Q != 0) {
R = Q % radix;
returns = base.charAt(R) + returns;
Q /= radix;
}
if(N == 0) {
return String.valueOf(base.toCharArray()[0]);
}
return N < 0 ? "-" + returns : returns;
}
This supports negative numbers and custom bases.
Decimal Addon:
public static String customBase (double N, String base) {
String num = (String.valueOf(N));
String[] split = num.split("\\.");
if(split[0] == "" || split[1] == "") {
return "";
}
return customBase(Integer.parseInt(split[0]), base)+ "." + customBase(Integer.parseInt(split[1]), base);
}
This can be helpful to you.The operation being performed on the 4 digit alphanumeric String and decimal number below 1679615. You can Modify code accordingly.
char[] alpaNum = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ".toCharArray();
String currentSeries = "";
int num = 481261;
String result = "";
String baseConversionStr = "";
boolean flag = true;
do
{
baseConversionStr = Integer.toString(num % 36) + baseConversionStr;
String position = "";
if(flag)
{
flag = false;
position = baseConversionStr;
}
else
{
position = Integer.toString(num % 36);
}
result += alpaNum[new Integer(position)];
num = num/36;
}
while (num > 0);
StringBuffer number = new StringBuffer(result).reverse();
String finalString = "";
if(number.length()==1)
{
finalString = "000"+articleNo;
}
else if(number.length()==2)
{
finalString = "00"+articleNo;
}
else if(number.length()==3)
{
finalString = "0"+articleNo;
}
currentSeries = finalString;

Categories