I have problem with my algorithm, I tried with my sample data noted below. And I don't understand why the result is not what I thought at all. For example when i = 3(n) and j = 2(n). The q should have output 2 but it's equal to 1. I guess the cause could just be that the while loop working was having problems. But I don't know the reason why. Please someone help me! Thank you very much
Running method
public static void compareStringToString(String str1, String str2) {
ArrayList<Integer> numSames = new ArrayList<Integer>();
int p = 0, n; // p - Maximum number of similar characters, n - the number of characters of the longer string
// str1 = "slcnsicnn"
// str2 = "ahnscnn"
int i = 0, j = 0;
if (str1.length() >= str2.length()) {
n = str1.length();
for (i = 0; i < n; i++) {
for (j = 0; j < str2.length(); j++) {
if (str1.charAt(i) == str2.charAt(j)) {
p = 0;
while (str1.charAt(i + p) == str2.charAt(j + p)) {
p++;
if ((i + p < n) || (j + p < str2.length())) {
break;
}
}
numSames.add(p);
}
}
}
System.out.println("The similarity of the two strings is: " + (((float)
Collections.max(numSames)) / n) * 100 + "%");
else {
n = str2.length();
// TODO Same things
}
Running Screen
**
I did as you said. I created a new method to split the work. Indeed, when I did that, my mind became clearer. And more specifically, I was able to run it smoothly without errors. Or maybe there are some more minor bugs that I haven't noticed yet. But it's really great like a little bit of a burden. Once again thank you very much for your kind advice.
**
// Get the number of similar characters after a pair of similar characters of 2 strings
public static int getNumSimilarAfterChar(String str1, String str2, int indexStr1, int indexStr2) {
int numChar = 0; // It's both a count and an index
// Substrings to work with algorithm
String subStr1;
String subStr2;
if (str1.charAt(indexStr1) == str2.charAt(indexStr2)) {
// Cut substring from highlighted part
subStr1 = str1.substring(indexStr1);
subStr2 = str2.substring(indexStr2);
while (subStr1.charAt(numChar) == subStr2.charAt(numChar)) {
numChar++;
if ((numChar >= (subStr1.length() - 1)) || (numChar >= (subStr2.length() - 1))) {
break;
}
}
return numChar + 1;
} else {
return numChar;
}
}
// Given any two strings of characters, compare the match of these two strings
/**
* Compare the match of string 1 vs string 2
*
* #param str1
* #param str2
*/
public static void compareStringToString(String str1, String str2) {
ArrayList<Integer> numSames = new ArrayList<Integer>();
// maxSimilar - maximum number of similar characters, totalLength - the number of characters of longer string
int numSimilar = 0, totalLength;
// slcnsicnn
// ahnscnn
int i = 0, j = 0;
// If string 1 is longer than string 2
if (str1.length() >= str2.length()) {
totalLength = str1.length();
for (i = 0; i < totalLength; i++) {
for (j = 0; j < str2.length(); j++) {
// Browse until you come across two similar characters
if (str1.charAt(i) == str2.charAt(j)) {
numSimilar = MyStrings.getNumSimilarAfterChar(str1, str2, i, j);
numSames.add(numSimilar);
System.out.println(numSames.toString());
}
}
}
// Get the max value in a list of how many identical characters are generated
System.out.println("The similarity of the two strings is: " + (((float) Collections.max(numSames)) / totalLength) * 100 + "%");
} else {
totalLength = str2.length();
// TODO Same things
}
}
Related
I am trying to solve ASCII distance problem for any given two strings. I have written the code to check for unmatched characters between two strings and calculated partial ascii distance. But I still need to compare two strings ( eg. as below. ) and come up with a common string that can be built out of those strings. Here is the example as below.
Let's say s1="elete" s2="leet"
Expected Output:
"let"
How can I identify the extra characters from both strings and come up with a common string in case of above example?
My code looks like this as below and what it does is compare two strings and calculate ASCII score for unmatched characters between two strings.
Code:
class Solution {
public int minimumDeleteSum(String s1, String s2) {
int sum = 0;
char[] cstr1 = s1.toCharArray();
char[] cstr2 = s2.toCharArray();
String res = compareCharacters( cstr1,cstr2 );
sum += Integer.parseInt( res.split(",")[1] );
String news1 = res.split(",")[0];
res = compareCharacters( cstr2,cstr1 );
sum += Integer.parseInt( res.split(",")[1] );
String news2 = res.split(",")[0];
/*Would like to add the code here to get all characters that are not allowing to build a common string and get their ASCII values.How do I approach this problem? */
return sum;
}
public String compareCharacters( char[] cstr1, char[] cstr2 ){
int ascii_score = 0;
int flag = 0;
StringBuilder sb = new StringBuilder();
for( int i=0;i<cstr1.length;i++ ){
flag = 0;
for( int j=0;j<cstr2.length;j++ ){
if( cstr1[i] == cstr2[j] )
flag++;
}
if( flag == 0 ){
ascii_score += (int)cstr1[i];
cstr1[i] = '\0';
}
if( flag>0 )
sb.append(cstr1[i]);
}
return sb.toString()+','+Integer.toString(ascii_score);
}
}
Please let me know if any questions. Thanks in advance!!
Duplicate of https://stackoverflow.com/a/51334221/1139196. I altered the code slightly to match with your question.
import java.util.Arrays;
import java.util.List;
public class LongestCommonSubstring {
public static char[] lcs(List l1, List l2) {
int[][] d = new int[l1.size() + 1][l2.size() + 1];
for (int i1 = 1; i1 <= l1.size(); i1++) {
for (int i2 = 1; i2 <= l2.size(); i2++) {
if (l1.get(i1 - 1).equals(l2.get(i2 - 1))) {
d[i1][i2] = d[i1 - 1][i2 - 1] + 1;
} else {
d[i1][i2] = Math.max(d[i1 - 1][i2], d[i1][i2 - 1]);
}
}
}
int i1 = l1.size(), i2 = l2.size();
char[] result = new char[d[i1][i2]];
while (i1 > 0 && i2 > 0) {
if (l1.get(i1 - 1).equals(l2.get(i2 - 1))) {
result[d[i1][i2] - 1] = ((String) l1.get(i1 - 1)).charAt(0);
i1 -= 1;
i2 -= 1;
} else if (d[i1][i2] == d[i1 - 1][i2]) {
i1 -= 1;
} else {
i2 -= 1;
}
}
return result;
}
public static void main(String[] args) {
List l1 = Arrays.asList("elete".split(""));
List l2 = Arrays.asList("leet".split(""));
System.out.println(new String(lcs(l1, l2)));
}
}
This program is throwing java.lang.StringIndexOutOfBoundsException.
Prime numbers in a single long string: "2357111317192329..."
Test cases
Inputs:
(int) n = 0
Output:
(string) "23571"
Inputs:
(int) n = 3
Output:
(string) "71113"
public class Answer {
public static String answer(int n) {
int i = 0;
int num = 0;
String primeNumbers = "";
char[] ar = new char[5];
for (i = 1; i <= 10000; i++) {
int counter = 0;
for (num = i; num >= 1; num--) {
if (i % num == 0) {
counter = counter + 1;
}
}
if (counter == 2) {
primeNumbers = primeNumbers + i;
}
}
ar[0] = primeNumbers.charAt(n);
ar[1] = primeNumbers.charAt(n + 1);
ar[2] = primeNumbers.charAt(n + 2);
ar[3] = primeNumbers.charAt(n + 3);
ar[4] = primeNumbers.charAt(n + 4);
return String.valueOf(ar);
}
}
try this solution:
public class Answer {
public static String answer(int n) {
StringBuilder primeNumberString = new StringBuilder(0);
int currentPrimeNumber = 2;
while (primeNumberString.length() < n+5) {
primeNumberString.append(currentPrimeNumber);
currentPrimeNumber++;
for (int index = 2; index < currentPrimeNumber; index++) {
if (currentPrimeNumber % index == 0) {
currentPrimeNumber++;
index = 2;
} else {
continue;
}
}
}
return primeNumberString.toString().substring(n, n+5)
}
}
=======================================================
EDIT
The problem statement suggests that the required output from the method you have written should be a string of length 5 and it should be from 'n' to 'n+4'.
Our goal should be to come up with a solution that gives us the string from n to n+4 using as less resources as possible and as fast as possible.
In the approach you have taken, you are adding in your string, all the prime numbers between 0 and 10000. Which comes up to about 1,229 prime numbers. The flaw in this approach is that if the input is something like 0. You are still building a string of 1,229 prime numbers which is totally unnecessary. If the input is something like 100000 then the error you are facing occurs, since you don't have a big enough string.
The best approach here is to build a string up to the required length which is n+5. Then cut the substring out of it. It's simple and efficient.
Probably you don't generate enough length of the string and given value out of your length of string.
I would recommend you to check your program on max value of given N. Also I would recommend you to not use String (read about creating a new object each time when you concatenate String) and simplify the second loop.
public static String answer(int n) {
StringBuilder sb = new StringBuilder("");
char[] ar = new char[5];
for (int i = 2; i <= 10000; i++) {
boolean flag = true;
for (int j = 2; j*j <= i; j++) {
if(i%j==0) {
flag = false;
break;
}
}
if(flag) {
sb.append(i);
}
}
ar[0] = sb.charAt(n);
ar[1] = sb.charAt(n + 1);
ar[2] = sb.charAt(n + 2);
ar[3] = sb.charAt(n + 3);
ar[4] = sb.charAt(n + 4);
return String.valueOf(ar);
}
I am trying to compress a string by turning it in to letters and numbers. Example:
INPUT: AAAAbbWWWW
OUTPUT: A4-b2-W4
Here is the problem I am running in to:
When I run it with the query "aaaaaaa", I get "a7".
When I run it with the query "aaaaaaaaaaaabbbbbbbbbbbbbbbbbbbbbbbbbbb", I get "a12-b2-b2-b2-b2-b2-b2-b2-b2-b2-b2-b2-b2-b2-b2".
My code is
List<Character> chars = new ArrayList<Character>();
for (int i = 0; i < toCompress.length(); i++) {
chars.add(toCompress.charAt(i));
}
List<String> bits = new ArrayList<String>();
for (int i = 0; i < chars.size(); i++) {
char toMatch = chars.get(i);
int matching = 1;
for (int dontuse = i; dontuse < chars.size(); dontuse++) {
int x = dontuse + 1;
if (x >= chars.size()) {
continue;
}
if (chars.get(x) == toMatch && (x - 1 == matching)) {
matching++;
}
}
if (!bits.contains(toMatch + "" + matching)) {
bits.add(toMatch + "" + (matching + 1));
i = i + matching;
}
}
String compressed = "";
for (int y = 0; y < bits.size(); y++) {
if (y == (bits.size() - 1)) {
compressed += bits.get(y);
} else {
compressed += bits.get(y) + "-";
}
}
return compressed;
Can anyone tell me how to stop it from only counting to two in every segment but the first?
A simple algorithm for your problem would be the following:
private static String compress(String str) {
StringBuilder compressed = new StringBuilder();
int i = 0;
while (i < str.length()) {
int length = 1;
while (i < str.length() - 1 && str.charAt(i) == str.charAt(i+1)) {
length++;
i++;
}
compressed.append(str.charAt(i)).append(length).append('-');
i++;
}
return compressed.deleteCharAt(compressed.length() - 1).toString();
}
It goes like this: while the character of the input String at index i is the same as the following character, we increment a length. As a result, length is then equal to the number of following characters that are the same.
When we hit a different character, we stop the loop, store the current character and its length, and repeat all this again for the next character.
Note that this algorithm will "compress" the String b into b1. You did not specify how it should behave on such Strings. If you don't want to this, you can simply add a check on length before it is appended to the current compressed String.
Alright, I fixed it. Here is what I did:
List<Character> chars = new ArrayList<Character>();
List<Character> oChars = new ArrayList<Character>();
for (int i = 0; i < toCompress.length(); i++) {
chars.add(toCompress.charAt(i));
}
for (char c : chars) {
if (!oChars.contains(c)) {
oChars.add(c);
}
}
HashMap<Character, Integer> map = new HashMap<Character, Integer>();
for (int i = 0; i < chars.size(); i++) {
try {
map.put(chars.get(i), map.get(chars.get(i)) + 1);
} catch (NullPointerException ex) {
map.put(chars.get(i), 1);
}
}
String compressed = "";
for (char c : oChars) {
int amount = map.get(c);
compressed += c + "" + amount + "-";
}
StringBuilder b = new StringBuilder(compressed);
b.replace(compressed.lastIndexOf("-"), compressed.lastIndexOf("-") + 1, "" );
compressed = b.toString();
return compressed;
Well, your logic doesn't really work. In fact, it's pretty hard to understand what you are trying to do here.
The place where you add to bits is the important part, because at the end you basically display what's in bits. So let's look at that part.
if (!bits.contains(toMatch + "" + matching)) {
bits.add(toMatch + "" + (matching + 1));
i = i + matching;
}
So it's important to see where you change the matching.
The first loop runs fine verifying against the a. But your problem is in this condition:
if (chars.get(x) == toMatch && (x - 1 == matching)) {
matching is 1 at the beginning of the inner loop. So as soon as you are into ranges of i that are beyond 0 and 1, x - 1 is not going to be equal to matching, and that means that matching will not change, it will stay at 1.
So except your first character, you'll never get a correct number in matching, because it will never be incremented. There is no point in comparing a running index to a count.
This code supposed to output the longest run on which a character in a string has a consecutive runs of itself. Though the problem is that it outputs: 8 (which should be 5 instead). I just would like to ask what seems to be the problem regarding this code.
public class Sample {
public static void main(String[] args) {
String setofletters = "aaakkcccccczz"; /* 15 */
int output = runLongestIndex(setofletters);
System.out.println("Longest run that first appeared in index:" + output);
}
public static int runLongestIndex(String setofletters) {
int ctr = 0;
int ctrstor = 0;
int ii = 0;
int output = 0;
// loops until the last character in the string
for (int i = 0; i < setofletters.length() - 1; i++) {
// checks if the letter is the same to the next
if (setofletters.charAt(i) == setofletters.charAt(i++)) {
ctr++;
ii = i++;
// loops until the letter in the index is no longer equal
while (setofletters.charAt(i) == setofletters.charAt(ii)) {
ii++;
ctr++;
}
if (ctr > ctrstor) {
output = i;
}
// storing purposes
ctrstor = ctr;
}
// resets the counter
ctr = 0;
}
return output;
}
}
UPDATE Sorry, I misunderstood your question a bit, you need to make the following changes in your code to make it work.(lines with comments)
public static int runLongestIndex(String setofletters){
int ctr = 1; // every character is repeated at least once, so you should initialize it to 1, not 0
int ctrstor = 0;
int ii = 0;
int output = 0;
for (int i = 0; i < setofletters.length() - 1; i++) {
if (i < setofletters.length() - 1 && setofletters.charAt(i) == setofletters.charAt(i+1)) { // i++ is not same as i+1
ctr++;
ii = i+1; // i++ is not same as i+1
while (setofletters.charAt(i) == setofletters.charAt(ii)) {
ii++;
ctr++;
}
if (ctr > ctrstor) {
output = i;
}
ctrstor = ctr;
}
ctr = 1; // for the same reason I mentioned above
}
return output;
}
EDIT : the easiest way to write your code is :
public static int runLongestIndex(String setofletters){
int ctr = 1;
int output = 0;
int j=0;
for(int i=0; i<setofletters.length()-1;i++){
j=i;
while(i <setofletters.length()-1 && setofletters.charAt(i)==setofletters.charAt(i+1)){
i++;
ctr++;
}
if(ctr>output){
output=j;
}
ctr = 1;
}
return output;
}
Why are you assigning i to output? You should assign ctr to output.
change
if(ctr>ctrstor){
output=i;
}
to
if(ctr>ctrstor){
output=ctr;
}
and also I think you should change
if(setofletters.charAt(i)==setofletters.charAt(i++))
to
if(i<setofletters.length()-1 && setofletters.charAt(i)==setofletters.charAt(i+1)){
and you should intialize ctr to 1 but not 0 because every character is repeated at least once.
I'll give you a Scala implementation for that problem.
Here it is the automatic test (in BDD style with ScalaTest)
import org.scalatest._
class RichStringSpec extends FlatSpec with MustMatchers {
"A rich string" should "find the longest run of consecutive characters" in {
import Example._
"abceedd".longestRun mustBe Set("ee", "dd")
"aeebceeedd".longestRun mustBe Set("eee")
"aaaaaaa".longestRun mustBe Set("aaaaaaa")
"abcdefgh".longestRun mustBe empty
}
}
Following is the imperative style implementation, with nested loops and mutable variables as you would normally choose to do in Java or C++:
object Example {
implicit class RichString(string: String) {
def longestRun: Set[String] = {
val chunks = mutable.Set.empty[String]
val ilen = string.length
var gmax = 0
for ((ch, curr) <- string.zipWithIndex) {
val chunk = mutable.ListBuffer(ch)
var next = curr + 1
while (next < ilen && string(next) == ch) {
chunk += string(next)
next = next + 1
}
gmax = chunk.length max gmax
if (gmax > 1) chunks += chunk.mkString
}
chunks.toSet.filter( _.length == gmax )
}
}
}
Following is a functional-style implementation, hence no variables, no loops but tail recursion with result accumulators and pattern matching to compare each character with the next one (Crazy! Isn't it?):
object Example {
implicit class RichString(string: String) {
def longestRun: Set[String] = {
def recurse(chars: String, chunk: mutable.ListBuffer[Char], chunks: mutable.Set[String]): Set[String] = {
chars.toList match {
case List(x, y, _*) if (x == y) =>
recurse(
chars.tail,
if (chunk.isEmpty) chunk ++= List(x, y) else chunk += y,
chunks
)
case Nil =>
// terminate recursion
chunks.toSet
case _ => // x != y
recurse(
chars.tail,
chunk = mutable.ListBuffer(),
chunks += chunk.mkString
)
}
}
val chunks = recurse(string, mutable.ListBuffer(), mutable.Set.empty[String])
val max = chunks.map(_.length).max
if (max > 0) chunks.filter( _.length == max ) else Set()
}
}
}
For example, for the given "aeebceeedd" string, both implementations above will build the following set of chunks (repeating characters)
Set("ee", "eee", "dd")
and they will filter those chunks having the maximum length (resulting "eee").
This code should work for any length of string sequence.
public class LongestStringSequqnce {
static String myString = "aaaabbbbcccchhhhiiiiibbbbbbbbbccccccc";
static int largestSequence = 0;
static char longestChar = '\0';
public static void main(String args[]) {
int currentSequence = 1;
char current = '\0';
char next = '\0';
for (int i = 0; i < myString.length() - 1; i++) {
current = myString.charAt(i);
next = myString.charAt(i + 1);
// If character's are in sequence , increase the counter
if (current == next) {
currentSequence += 1;
} else {
if (currentSequence > largestSequence) { // When sequence is
// completed, check if
// it is longest
largestSequence = currentSequence;
longestChar = current;
}
currentSequence = 1; // re-initialize counter
}
}
if (currentSequence > largestSequence) { // Check if last string
// sequence is longest
largestSequence = currentSequence;
longestChar = current;
}
System.out.println("Longest character sequence is of character "
+ longestChar + " and is " + largestSequence + " long");
}
}
Source : http://www.5balloons.info/program-java-code-to-find-longest-character-sequence-in-a-random-string/
if(ctr>ctrstor){
output=i;
}
//storing purposes
ctrstor=ctr;
This looks like the problem. So if you find 8 consecutive characters, it will set output to 8, and proceed. The next time thru, it finds 3 consecutive characters, so doesn't set output, but sets ctrstor. Next time thru it finds 4 consecutive characters, and this will set output to 4
There are few traps in the code that your logic felt in:
Code incorrectly assumes that there is always next character to compare current one.
This fails for string like "a" or the last character in any string.
Code does not store the max count of characters but only the max index (i).
MaxCount is needed to compare the next chars sequence size.
Loop for and loop while repeat the same subset of characters.
Also variable name style makes it harder to understand the code.
After correcting above
public static int runLongestIndex(String setofletters) {
int maxCount = 0;
int maxIndex = 0;
// loops each character in the string
for (int i = 0; i < setofletters.length() - 1; ) {
// new char sequence starts here
char currChar = setofletters.charAt(i);
int count = 1;
int index = i;
while ( (index < setofletters.length() - 1) &&
(currChar == setofletters.charAt(++index)) ) {
count++;
}
if (count > maxCount) {
maxIndex = i;
maxCount = count;
}
i = index;
}
return maxIndex;
}
See Java DEMO
I think you don't need an internal loop:
public static int runLongestIndex(String setofletters) {
if (setofletters == null || setofletters.isEmpty()) {
return -1;
}
int cnt = 1;
char prevC = setofletters.charAt(0);
int maxCnt = 1;
//char maxC = prevC;
int maxRunIdx = 0;
int curRunIdx = 0;
for (int i = 1; i < setofletters.length(); i++){
final char c = setofletters.charAt(i);
if (prevC == c) {
cnt++;
} else {
if (cnt > maxCnt) {
maxCnt = cnt;
//maxC = prevC;
maxRunIdx = curRunIdx;
}
cnt = 1;
curRunIdx = i;
}
prevC = c;
}
if (setofletters.charAt(setofletters.length() - 1) == prevC) {
if (cnt > maxCnt) {
//maxC = prevC;
maxCnt = cnt;
maxRunIdx = curRunIdx;
}
}
return maxRunIdx;
}
and this code:
System.out.println(runLongestIndex("aaakkcccccczz"));
gives you
5
This is how a "colleague" of mine is understanding to write readable code in order to solve this problem, even if this is working :)
public static int count (String str) {
int i = 0;
while(i < str.length()-1 && str.charAt(i)==str.charAt(i+1))
i ++;
return ++i;
}
public static int getLongestIndex(String str){
int output = 0;
for(int i=0, cnt = 1, counter = 0 ; i<str.length() - 1;i += cnt, cnt = count(str.substring(i)), output = (counter = (cnt > counter ? cnt : counter)) == cnt ? i : output);
return output;
}
int indexOfLongestRun(String str) {
char[] ar = str.toCharArray();
int longestRun = 0;
int lastLongestRun = 0;
int index = 0;
for(int i = ar.length-1; i>0; i--){
if(ar[i] == ar[i-1]){
longestRun++;
}else{
if(longestRun > lastLongestRun){
lastLongestRun = longestRun;
longestRun = 0;
index = i;
}
}
}
return index;
Well, the solution a bit depends on the additional requirements. Here is the code which returns the FIRST longest sequence of a repeated character int the given string, meaning if you have a second sequence with the same length you never get it out :(. But still, this is a simple and clear solution here, so good news - it works! :)
string = 'abbbccddddddddeehhhfffzzzzzzzzdddvyy'
longest_sequence = ''
for i in range(len(string)):
is_sequence = True
ch_sequence = ''
while is_sequence:
ch_sequence += string[i]
if i+1 < len(string) and string[i]==string[i+1]:
i += 1
else:
is_sequence = False
if len(ch_sequence) > len(longest_sequence):
longest_sequence = ch_sequence
print (longest_sequence)
#Paolo Angioletti already provided an answer using Scala, but it's more complicated than it needs to be. The idea is not very different from Run-length encoding. Time complexity O(n).
def longestConsecutive(s: String): (Char, Int) = {
Iterator.iterate(('\u0000', 0, 0)) { case (ch, longestRun, i) =>
val run = (i until s.length)
.takeWhile(s(_) == s(i))
.size
if (run > longestRun) (s(i), run, i + run)
else (ch, longestRun, i + run)
}
.dropWhile(i => s.isDefinedAt(i._3))
.take(1)
.map(x => (x._1, x._2))
.next()
}
Tested with:
("s", "ch", "n")
----------------
("", '\u0000', 0),
("a", 'a', 1),
("aabcddbbbea", 'b', 3),
("abcddbbb", 'b', 3),
("cbccca", 'c', 3)
#include <iostream>
#include<algorithm>
using namespace std;
int main() {
string s="abbcccccbbffffffffff";
//cin>>s;
int count=1;
int maxcount=1;
int start=0;
int ps=0;
for (int i=0;i<s.size()-1;i++)
{
if(s.at(i)==s.at(i+1))
{
count +=1;
maxcount=max(maxcount,count);
}
else
{
ps=max(ps,start+count);
count =1;
start=i;
}
}
for(int i=1;i<=maxcount;i++)
{
cout<<s.at(i+ps);
}
// your code goes here
return 0;
}
This is the simplest I can think of and it will print the number of the longest sequenced identical characters in a one line string.
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
String s = scanner.nextLine();
scanner.close();
int count = 0;
int curCount = 1;
for (int i = 0; i < s.length() -1; i++) {
if (s.charAt(i) == s.charAt(i + 1)) {
curCount++;
if (curCount > count) {
count = curCount;
}
}else {
if (curCount > count) {
count = curCount;
}
curCount = 1;
}
}
System.out.println(count);
}
In my project I have to deal with multiplication of big numbers ( greater then java.long ) stared in my own BigNumber class as int[]. Basically I need to implement something like this :
157 x
121 y
----
157 result1
314 + result2
157 + result3
------
18997 finalResult
But how do I implement it?
I thought about expanding result2,3 with zeros (3140, 15700) and adding them. But first I somehow need to navigate between each digit of y and multiply it by each digit of x.
Use the diagonal approach. Make an array, and multiply each digit by each other digit and fill in the numbers in each cell.
36 x 92
3 6
+-----+-----+
| 2 / | 5 / |
9 | / | / |
| / 7 | / 4 |
+-----+-----+
| 0 / | 1 / |
2 | / | / |
| / 6 | / 2 |
+-----+-----+
Add the numbers on each diagonal. Move from the least-significant digit (at the lower right) to the most (upper left).
2 2 (least-significant)
(6 + 1 + 4) = 11 (make this 1, and carry the 1 to the next digit) 1
(5 + 7 + 0 + 1(carried)) = 13 (make this 3, and carry the 1) 3
2 + 1(carried) = 3 3 (most-significant)
The answer's 3312.
Make a two-dimensional array of your digits. Fill the array with the multiplications of the single digits together.
Write some logic to scrape the diagonals as I did above.
This should work for arbitrarily large numbers (as long as you still have memory left).
Here's the code I had written. Basically same as manual multiplication. Pass the two big numbers as strings to this function, the result is returned as a string.
public String multiply(String num1, String num2){
int product, carry=0, sum=0;
String result = new String("");
String partial = new String("");
ArrayList<String> partialList = new ArrayList<String>();
/* computing partial products using this loop. */
for(int j=num2.length()-1 ; j>=0 ; j--) {
for(int i=num1.length()-1 ; i>=0 ; i--) {
product = Integer.parseInt((new Character(num1.charAt(i))).toString()) *
Integer.parseInt((new Character(num2.charAt(j))).toString()) + carry;
carry = product/10;
partial = Integer.toString(product%10) + partial;
}
if(carry != 0)
partial = Integer.toString(carry) + partial;
partialList.add(partial);
partial = "";
carry = 0;
}
/* appending zeroes incrementally */
for(int i=0 ; i<partialList.size() ; i++)
partialList.set(i, partialList.get(i) + (Long.toString( (long)java.lang.Math.pow(10.0,(double)i))).substring(1) );
/* getting the size of the largest partial product(last) */
int largestPartial = partialList.get(partialList.size()-1).length();
/* prefixing zeroes */
int zeroes;
for(int i=0 ; i<partialList.size() ; i++) {
zeroes = largestPartial - partialList.get(i).length();
if(zeroes >= 1)
partialList.set(i, (Long.toString( (long)java.lang.Math.pow(10.0,(double)zeroes))).substring(1) + partialList.get(i) );
}
/* to compute the result */
carry = 0;
for(int i=largestPartial-1 ; i>=0 ; i--) {
sum = 0;
for(int j=0 ; j<partialList.size() ; j++)
sum = sum + Integer.parseInt(new Character(partialList.get(j).charAt(i)).toString());
sum = sum + carry;
carry = sum/10;
result = Integer.toString(sum%10) + result;
}
if(carry != 0)
result = Integer.toString(carry) + result;
return result;
}
I would avoid the headaches of writing your own and just use the java.math.BigInteger class. It should have everything you need.
Separating out the carrying and the digit multiplication:
def carries(digitlist):
digitlist.reverse()
for idx,digit in enumerate(digitlist):
if digit>9:
newdigit = digit%10
carry = (digit-newdigit)/10
digitlist[idx] = newdigit
if idx+1 > len(digitlist)-1:
digitlist.append(carry)
else:
digitlist[idx+1] += carry
digitlist.reverse()
return True
def multiply(first,second):
digits = [0 for place in range(len(first)+len(second))]
for fid,fdig in enumerate(reversed(first)):
for sid,sdig in enumerate(reversed(second)):
offset = fid+sid
mult = fdig*sdig
digits[offset] += mult
digits.reverse()
carries(digits)
return digits
def prettify(digitlist):
return ''.join(list(`i` for i in digitlist))
Then we can call it:
a = [1,2,3,4,7,6,2]
b = [9,8,7,9]
mult = multiply(a,b)
print prettify(a)+"*"+prettify(b)
print "calc:",prettify(mult)
print "real:",int(prettify(a))*int(prettify(b))
Yields:
1234762*9879
calc: 12198213798
real: 12198213798
Of course the 10s in the carries function and the implicit decimal representation in prettify are the only thing requiring this to be base 10. Adding an argument could make this base n, so you could switch to base 1000 in order to reduce the numbers of blocks and speed up the calculation.
I have implemented this in C++. refer to this for logic...
#include <iostream>
#include <deque>
using namespace std;
void print_num(deque<int> &num) {
for(int i=0;i < num.size();i++) {
cout<<num[i];
}
cout<<endl;
}
deque<int> sum(deque<int> &oppA, deque<int> &oppB) {
if (oppA.size() == 0) return oppB;
if (oppB.size() == 0) return oppA;
deque<int> result;
unsigned int carry = 0;
deque<int>::reverse_iterator r_oppA = oppA.rbegin();
deque<int>::reverse_iterator r_oppB = oppB.rbegin();
while ((r_oppA != oppA.rend()) && (r_oppB != oppB.rend())) {
int tmp = *r_oppA + *r_oppB + carry;
result.push_front(tmp % 10);
carry = tmp / 10;
r_oppB++;
r_oppA++;
}
while (r_oppA != oppA.rend()) {
int tmp = *r_oppA + carry;
result.push_front(tmp % 10);
carry = tmp / 10;
r_oppA++;
}
while (r_oppB != oppB.rend()) {
int tmp = *r_oppB + carry;
result.push_front(tmp % 10);
carry = tmp / 10;
r_oppB++;
}
return result;
}
deque<int> multiply(deque<int>& multiplicand, deque<int>& multiplier) {
unsigned int carry = 0;
deque<int> result;
int deci_cnt = 0;
deque<int>::reverse_iterator r_multiplier = multiplier.rbegin();
deque<int> tmp_result;
while (r_multiplier != multiplier.rend()) {
for (int i=0; i<deci_cnt ;i++) {
tmp_result.push_front(0);
}
deque<int>::reverse_iterator r_multiplicand = multiplicand.rbegin();
while (r_multiplicand != multiplicand.rend()) {
int tmp = (*r_multiplicand) * (*r_multiplier) + carry;
tmp_result.push_front(tmp % 10);
carry = tmp / 10;
r_multiplicand++;
}
if (carry != 0) {
tmp_result.push_front(carry);
carry = 0;
}
result = sum(result, tmp_result);
deci_cnt++;
tmp_result.clear();
r_multiplier++;
}
return result;
}
deque<int> int_to_deque(unsigned long num) {
deque<int> result;
if (num == 0) {
result.push_front(0);
}
while (num > 0) {
result.push_front(num % 10);
num = num / 10;
}
return result;
}
int main() {
deque<int> num1 = int_to_deque(18446744073709551615ULL);
deque<int> num2 = int_to_deque(18446744073709551615ULL);
deque<int> result = multiply(num1, num2);
print_num(result);
return 0;
}
Output: 340282366920928463426481119284349108225
You're going to have to treat each int in the array as a single "digit". Instead of using base 10 where each digit goes from 0 to 9, you'll have to use base 2^32 = 4294967296, where every digit goes from 0 to 4294967295.
I would first implement addition, as your algorithm for multiplication might use addition as an auxiliary.
As this is for homework I'll give a few hints.
You could approach it the same way you show your example, using strings to hold numbers of any length and implementing:
add one number to another
multiply as your example by appending zeroes and calling the addition method per step (so for multiply with 20, append the "0" and addd that number twice
The addition method you can build by retrieving the char[] from the strings, allocate a result char[] that is 1 longer than the longest and add like you would do on paper from the end back to the start of both arrays.
The end result will not be the best performing solution, but it it easy to show it is correct and will handle any length numbers (as long they will fit a Java string.)
Update
Ok, if you solved adding two numbers, you could:
implement multiplication by 10
implement multiplication by repeated addition like in your example
or:
implement multiplication by 2 (left shift)
implement a binary multiplication via the same concept, only this time x 2 and add once
to illustrate the latter,
13
5 x
----
13 x 1
26 x 0
52 x 1
---- +
65
note that the 1 0 1 are the bits in the number (5) you multiply with and 26 = 13 x 2, 52 = 26 x 2. Your get the idea :-)
did it my own way :
int bigger = t1.length;
int smaller = t2.length;
int resultLength = bigger + smaller;
int []resultTemp = new int[resultLength];
int []result = new int[bigger + smaller];
int []temporary = new int[resultLength+1];
int z = resultLength-1;
int zet = z;
int step = 0;
int carry = 0;
int modulo = 0;
for(int i=smaller-1; i>=0; i--){
for(int k = bigger-1; k>= -1; k--){
if(k == -1 && carry != 0 ){
resultTemp[z] = carry;
carry = 0;
break;
}
else if(k == -1 && carry == 0){
resultTemp[z] = 0;
break;
}
resultTemp[z] = carry + t1[k]*t2[i];
carry = 0;
if( resultTemp[z] > 9 ){
modulo = resultTemp[z] % 10;
carry = resultTemp[z]/10;
resultTemp[z] = modulo;
}
else{
resultTemp[z] = resultTemp[z];
}
z--;
}
temporary = add(resultTemp, result);
result = copyArray(temporary);
resultTemp = clear(resultTemp);
z = zet;
step++;
z = z - step;
}
then I check the sign.
Since this is homework... Are you sure using an int array is your best shot?
I tried to implement something similar a year ago for performance in a research
project, and we ended up going with concatenated primitives..
Using this you can take advantage of what's already there, and "only" have to worry about overflows near the ends.. This might prove to be fairly simple when you implement your multiplication with <<'s (bit shift lefts) and additions..
Now if you want a real challenge try to implement a modulo... ;)
You can check the below solution which teaches us both multiplication and addition of bigger numbers. Please comment if it can be improved.
public static void main(String args[]) {
String s1 = "123666666666666666666666666666666666666666666666669999999999999999999999999666666666666666666666666666666666666666666666666666666666666666666";
String s2 = "45688888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888";
System.out.println(multiply(s1, s2));
}
private static String multiply(String s1, String s2) {
int[] firstArray = convert(s1);
int[] secondArray = convert(s2);
//System.out.println(Arrays.toString(firstArray));
//System.out.println(Arrays.toString(secondArray));
// pass the arrays and get the array which is holding the individual
// rows while we multiply using pen and paper
String[] result = doMultiply(firstArray, secondArray);
//System.out.println(Arrays.toString(result));
// Now we are almost done lets format them as we like
result = format(result);
//System.out.println(Arrays.toString(result));
//Add elements now and we are done
String sum="0";
for(String s:result){
sum=add(sum,s);
}
return sum;
}
private static String[] doMultiply(int[] firstArray, int[] secondArray) {
String[] temp = new String[secondArray.length];
for (int i = secondArray.length - 1; i >= 0; i--) {
int result = 0;
int carry = 0;
int rem = 0;
temp[secondArray.length - 1 - i] = "";
for (int j = firstArray.length - 1; j >= 0; j--) {
result = (secondArray[i] * firstArray[j]) + carry;
carry = result / 10;
rem = result % 10;
temp[secondArray.length - 1 - i] = rem
+ temp[secondArray.length - 1 - i];
}
// if the last carry remains in the last digit
if (carry > 0)
temp[secondArray.length - 1 - i] = carry
+ temp[secondArray.length - 1 - i];
}
return temp;
}
public static int[] convert(String str) {
int[] arr = new int[str.length()];
for (int i = 0; i < str.length(); i++) {
arr[i] = Character.digit(str.charAt(i), 10);
}
return arr;
}
private static String[] format(String[] result) {
for (int i = 0; i < result.length; i++) {
int j = 0;
while (j < i) {
result[i] += "0";
j++;
}
}
return result;
}
public static String add(String num1, String num2) {
//System.out.println("First Number :" + num1);
//System.out.println("Second Number :" + num2);
int max = num1.length() > num2.length() ? num1.length() : num2.length();
int[] numArr1 = new int[max];
int[] numArr2 = new int[max];
for (int i = 0; i < num1.length(); i++) {
numArr1[i] = Integer.parseInt(""
+ num1.charAt(num1.length() - 1 - i));
}
for (int i = 0; i < num2.length(); i++) {
numArr2[i] = Integer.parseInt(""
+ num2.charAt(num2.length() - 1 - i));
}
int carry = 0;
int[] sumArr = new int[max + 1];
for (int k = 0; k < max; k++) {
int tempsum = numArr1[k] + numArr2[k] + carry;
sumArr[k] = tempsum % 10;
carry = 0;
if (tempsum >= 10) {
carry = 1;
}
}
sumArr[max] = carry;
/* System.out.println("Sum :"
+ new StringBuffer(Arrays.toString(sumArr)).reverse()
.toString().replaceAll(",", "").replace("[", "")
.replace("]", "").replace(" ", ""));*/
return new StringBuffer(Arrays.toString(sumArr)).reverse().toString()
.replaceAll(",", "").replace("[", "").replace("]", "")
.replace(" ", "");
}
I think this will help you
import java.util.ArrayList;
import java.util.List;
public class Multiply {
static int len;
public static void main(String[] args) {
System.out.println(multiply("123456789012345678901","123456789012345678901");
}
private static ArrayList<Integer> addTheList(List<ArrayList<Integer>> myList) {
ArrayList<Integer> result=new ArrayList<>();
for(int i=0;i<len;i++)
{
result.add(0);
}
int index=0;
for(int i=0;i<myList.size();i++)
{
ArrayList<Integer> a=new ArrayList<>(myList.get(index));
ArrayList<Integer> b=new ArrayList<>(myList.get(index+1));
for (int j = 0; j < a.size()||j < b.size(); i++) {
result.add(a.get(i) + b.get(i));
}
}
return result;
}
private static ArrayList<Integer> multiply(ArrayList<Integer> list1, Integer integer) {
ArrayList<Integer> result=new ArrayList<>();
int prvs=0;
for(int i=0;i<list1.size();i++)
{
int sum=(list1.get(i)*integer)+prvs;
System.out.println(sum);
int r=sum/10;
int m=sum%10;
if(!(r>0))
{
result.add(sum);
}
else
{
result.add(m);
prvs=r;
}
if(!(i==(list1.size()-1)))
{
prvs=0;
}
}
if(!(prvs==0))
{
result.add(prvs);
}
return result;
}
private static ArrayList<Integer> changeToNumber(String str1) {
ArrayList<Integer> list1=new ArrayList<>();
for(int i=0;i<str1.length();i++)
{
list1.add(Character.getNumericValue(str1.charAt(i)));
}
return list1;
}
public static String multiply(String num1, String num2) {
String n1 = new StringBuilder(num1).reverse().toString();
String n2 = new StringBuilder(num2).reverse().toString();
int[] d = new int[num1.length()+num2.length()];
//multiply each digit and sum at the corresponding positions
for(int i=0; i<n1.length(); i++){
for(int j=0; j<n2.length(); j++){
d[i+j] += (n1.charAt(i)-'0') * (n2.charAt(j)-'0');
}
}
StringBuilder sb = new StringBuilder();
//calculate each digit
for(int i=0; i<d.length; i++){
int mod = d[i]%10;
int carry = d[i]/10;
if(i+1<d.length){
d[i+1] += carry;
}
sb.insert(0, mod);
}
//remove front 0's
while(sb.charAt(0) == '0' && sb.length()> 1){
sb.deleteCharAt(0);
}
return sb.toString();
}
}