How do i optimize this Java code for CyclicShift (Hackerearth question)? - java

I have written a solution for Cyclic shift question on Hackerearth.
You can find this question on Hackerearth -> Codemonk -> Arrays & String -> Cyclic shift.
This solution gives TLE for large testcases. How do i optimize this code.
It seems like Java does not handle strings efficiently. Same code in Python gets accepted.
import java.io.*;
import java.util.*;
class TestClass
{
public static void main(String[] args)
{
Scanner sc = new Scanner(System.in);
int T = sc.nextInt();
while(T-- > 0){
int N; int K;
N = sc.nextInt();
K = sc.nextInt();
String input = sc.next();
String B = "";
String inter = input;
int d = 0;
int period = -1;
for(int i = 0; i < N;i++){
if (B.compareTo(inter) < 0){
B = inter;
d = i;
}else if (B.compareTo(inter) == 0){
period = i - d;
break;
}
inter = inter.substring(1, inter.length()) + inter.substring(0, 1);
}
if(period == -1){
System.out.println(d + (K - 1L ) * N);
}else{
System.out.println(d + ((K - 1L) * period));
}
}
}
}
I tried fast IO, it did not help.
Please give me the Optimized Solution.
As suggested by maraca. Following solution does gets accepted.
import java.io.*;
import java.util.*;
class TestClass
{
static int compare(LinkedList<Character> A, LinkedList<Character> B){
Iterator<Character> i = A.iterator();
Iterator<Character> j = B.iterator();
if(A.size() == 0){ return -1;}
while (i.hasNext()) { // we know they have same length
char c = i.next();
char d = j.next();
if (c < d)
return -1;
else if (c > d)
return 1;
}
return 0;
}
public static void main(String[] args)
{
Scanner sc = new Scanner(System.in);
int T = sc.nextInt();
while(T-- > 0){
int N; int K;
N = sc.nextInt();
K = sc.nextInt();
String input = sc.next();
LinkedList<Character> B = new LinkedList<>();
int d = 0;
int period = -1;
LinkedList<Character> inter = new LinkedList<>();
for(char c: input.toCharArray()){inter.add(c);}
for(int i = 0; i < N;i++){
if (compare(B, inter) < 0){
B = new LinkedList<>(inter);
d = i;
}else if (compare(B, inter) == 0){
period = i - d;
break;
}
inter.add(inter.removeFirst());
}
if(period == -1){
System.out.println(d + (K - 1L ) * N);
}else{
System.out.println(d + ((K - 1L) * period));
}
}
}
}

Strings are immutable in Java. You could try to use LinkedList:
LinkdedList<Character> inter = new LinkedList<>(Arrays.stream(inter)
.boxed()
.collect(Collectors.toList()));
Alternatively:
LinkdedList<Character> inter = new LinkedList<>();
for (char c : input.toCharArray())
inter.add(c);
Then the shift becomes:
inter.add(inter.removeFirst());
And the comparison can be done as follows:
private int compare(List<Character> a, List<Character> b) {
Iterator<Character> i = a.iterator();
Iterator<Character> j = b.iterator();
while (i.hasNext()) { // we know they have same length
char c = i.next();
char d = j.next();
if (c < d)
return -1;
else if (c > d)
return 1;
}
return 0;
}

my solution
import java.io.*;
import java.util.*;
class TestClass
{
static int compare(LinkedList<Character> A, LinkedList<Character> B){
Iterator<Character> i = A.iterator();
Iterator<Character> j = B.iterator();
if(A.size() == 0){ return -1;}
while (i.hasNext()) { // we know they have same length
char c = i.next();
char d = j.next();
if (c < d)
return -1;
else if (c > d)
return 1;
}
return 0;
}
public static void main(String[] args)
{
Scanner sc = new Scanner(System.in);
int T = sc.nextInt();
while(T-- > 0){
int N; int K;
N = sc.nextInt();
K = sc.nextInt();
String input = sc.next();
LinkedList<Character> B = new LinkedList<>();
int d = 0;
int period = -1;
LinkedList<Character> inter = new LinkedList<>();
for(char c: input.toCharArray()){inter.add(c);}
for(int i = 0; i < N;i++){
if (compare(B, inter) < 0){
B = new LinkedList<>(inter);
d = i;
}else if (compare(B, inter) == 0){
period = i - d;
break;
}
inter.add(inter.removeFirst());
}
if(period == -1){
System.out.println(d + (K - 1L ) * N);
}else{
System.out.println(d + ((K - 1L) * period));
}
}
}
}

Related

Amstrong number return in blank result (java)

public class Amstrong {
public static void main(String[] args) {
for (int i = 100; i < 1000; i++) {
String a = String.valueOf(i);
int b = a.charAt(0);
int c = a.charAt(1);
int d = a.charAt(2);
int e = b * b * b + c * c * c + d * d * d;
if (e == i) {
System.out.println(i);
}
}
}
}
//Help me out please, no error occurred but the result returned in the blank
You are not converting the characters to digits correctly.
One of the possible ways to fix it:
int b = a.charAt(0)-'0';
int c = a.charAt(1)-'0';
int d = a.charAt(2)-'0';
Another way:
int b = Character.digit (a.charAt(0),10);
int c = Character.digit (a.charAt(1),10);
int d = Character.digit (a.charAt(2),10);
Either way will give your the output:
153
370
371
407
Another way you can do it is:
import java.util.*;
public class ArmstrongNumber3
{
public static void main(String args[]) {
Scanner sc = new Scanner(System.in);
System.out.println("Enter any number");
int n = sc.nextInt();
int b = n;
int sum = 0;
int d = 0;
while (n != 0) {
d = n % 10;
sum += (d * d * d);
n = n / 10;
}
if (sum == b) {
System.out.println("Armstrong");
} else
{
System.out.println("Not Armstrong");
}
}
}
import java.util.Scanner;
public class Amstrong {
public static void main(String args[]) {
Integer num, temp, len = 0, initVal;
double finalVal = 0;
Scanner scn = new Scanner(System.in);
System.out.println("Enter the number");
num = scn.nextInt();
initVal = num;
temp = num;
while (temp != 0) {
temp = temp / 10;
len++;
}
for (int i = 0; i <= len; i++) {
temp = num % 10;
finalVal = finalVal + Math.pow(temp, len);
num = num / 10;
}
if (Double.valueOf(initVal) == finalVal) {
System.out.println("Amstrong");
} else {
System.out.println("Not Amstrong");
}
}
}

JAVA // How do i make it case-insensitive?

import java.util.Random;
public class MergeSortEx {
public static void mergeSort(char[] array) {
sortArray(array, 0, array.length);
}
private static void sortArray(char[] array, int start, int end) {
if (end-start <2)
return;
int mid = (start + end) / 2;
sortArray(array, 0, mid);
sortArray(array, mid, end);
mergeArray(array, start, mid, end);
}
private static void mergeArray(char[] array, int start, int mid, int end) {
char[] temp = new char[end - start];
int t = 0, s = start, m = mid;
while (s < mid && m < end) {
if (array[s] < array[m])
temp[t++] = array[s++];
else
temp[t++] = array[m++];
}
while (s < mid) {
temp[t++] = array[s++];
}
while (m < end) {
temp[t++] = array[m++];
}
for(int i=start;i<end;i++) {
array[i]=temp[i-start];
}
}
public static void main(String[] args) {
char[] randomString = new char[20];
Random rnd = new Random();
for (int i = 0; i < 20; i++) {
if (i < 10)
randomString[i] = (char) (rnd.nextInt(6) + 'A');
else
randomString[i] = (char) (rnd.nextInt(6) + 'a');
}
System.out.println(randomString.length);
for (int i = 0; i < 20; i++)
System.out.print(randomString[i] + " ");
mergeSort(randomString);
System.out.println();
for (int i = 0; i < 20; i++)
System.out.print(randomString[i] + " ");
}
}
I used the translator.
It's a university algorithm assignment, Merge sort implemented successfully.
Now, capital letters come out first, and lowercase letters come out.
Can make the code case-insensitive?
I want the results to be like this.
ex) a A A B b C c c D d ...
plz help.
Instead of comparing using if (array[s] < array[m]) directly, convert the characters to uppercase before comparing, similar to what String.compareToIgnoreCase(...) does:
if (Character.toUpperCase(array[s]) < Character.toUpperCase(array[m]))
That is for sorting individual characters. For sorting String values, there are two ways to make a case-insensitive sort:
Use the predefined String.CASE_INSENSITIVE_ORDER Comparator.
stringList.sort(String.CASE_INSENSITIVE_ORDER);
Use a Collator:
Collator collator = Collator.getInstance(Locale.US);
stringList.sort(collator);
That will sort localized alphabets correctly, e.g. if you specified Locale.GERMANY, it would sort upper- and lower-case letters together, but will e.g. also sort Ð between D and E, and sort ß same as S.
Just replace:
while (s < mid && m < end) {
if (arr[s] < arr[m])
temp[t++] = arr[s++];
else
temp[t++] = arr[m++];
}
with
while (s < mid && m < end) {
if (Character.toLowerCase(arr[s]) < Character.toLowerCase(arr[m]))
temp[t++] = arr[s++];
else
temp[t++] = arr[m++];
}
If you want small letters come first like aAbbbBBBcCCCD then try following.
Instead of:
array[s] < array[m]
Use:
private static boolean charCompare(char a, char b) {
char ua = Character.toUpperCase(a);
char ub = Character.toUpperCase(b);
if(ua == ub) {
return a > b;
} else {
return ua < ub;
}
}
Output:
20
F E E A D A B C A E a e c f d f c a f e
a a A A A B c c C d D e e E E E f f f F

Ant colony optimization for TSP not getting the shortest path

I have implemented the algorithm according to this paper it's working well, but for certain tests, it doesn't get the shortest path,
here's the pseudo-code
Initialize
For t=1 to iteration number do
For k=1 to l do
Repeat until ant k has completed a tour
Select the city j to be visited next
With probability pij given by Eq. (1)
Calculate Lk
Update the trail levels according to Eqs. (2-4).
End
here's the code
import java.io.*;
import java.util.*;
import static java.lang.Math.*;
public class test2 {
private InputReader cin;
private PrintWriter cout;
double pheromones[][];
double distances[][];
double visibility[][];
static int n;
City[] city;
Ant[] ant;
int m;
int T;
double alpha = 1; // pheromone importance
double beta = 2; // visibility importance
double evaporation = 0.1;
double Q = 100.0;
static class City {
double x, y;
int id;
public City(double x, double y, int id) {
this.x = x;
this.y = y;
this.id = id;
}
}
static class Ant {
int whereAmI;
boolean[] visited;
double tourDistance;
LinkedList<Integer> citiesVisitedInOrder;
int cityEdges[][];
Ant(int whereAmI) {
this.whereAmI = whereAmI;
visited = new boolean[n + 1];
cityEdges = new int[n + 1][n + 1];
reset();
}
void reset() {
Arrays.fill(visited, false);
visited[whereAmI] = true;
for (int i = 1; i <= n; i++)
Arrays.fill(cityEdges[i], 0);
tourDistance = 0;
citiesVisitedInOrder = new LinkedList<>();
citiesVisitedInOrder.addLast(whereAmI);
}
}
//the actual algorithm iteration
/*
Initialize
For t=1 to iteration number do
For k=1 to l do
Repeat until ant k has completed a tour
Select the city j to be visited next
With probability pij given by Eq. (1)
Calculate Lk
Update the trail levels according to Eqs. (2-4).
End
*/
private void solve() {
n = cin.readInt();
initializeParameter();
//the main loop
for (int t = 0; t < T; t++) {
for (int i = 0; i < m; i++) {//for each ant
Ant current = ant[i];
for (int j = 0; j < n; j++) {//for each city
int currentAntsCity = current.whereAmI;
double highestProbability = 0;
int cityId = 1;
double sumNotiation = calculateSum(current.visited, currentAntsCity);
//traverse all non-visited cities and choose the best
boolean good = false;
for (int c = 1; c <= n; c++) {//remove the equal
if (!current.visited[c]) {
double prop = (pow(pheromones[currentAntsCity][c], alpha) * pow(visibility[currentAntsCity][c], beta))
/ sumNotiation;
if (prop >= highestProbability) {
highestProbability = prop;
cityId = c;
good = true;
}
}
}
if (good) {
current.tourDistance += distances[currentAntsCity][cityId];
current.cityEdges[currentAntsCity][cityId] = current.cityEdges[cityId][currentAntsCity] = 1;
current.citiesVisitedInOrder.addLast(cityId);
current.whereAmI = cityId;
current.visited[cityId] = true;
}
}//after n iteration i ant completes a tour
current.tourDistance += distances[current.citiesVisitedInOrder.getFirst()][current.citiesVisitedInOrder.getLast()];
}//update
for (int i = 1; i <= n; i++) {
for (int j = i + 1; j <= n; j++) {
double deltaPhermons = 0;
for (int a = 0; a < m; a++) {
if (ant[a].cityEdges[i][j] != 0) {
deltaPhermons += Q / ant[a].tourDistance;
}
}
pheromones[i][j] = pheromones[j][i] = pheromones[i][j] * evaporation + deltaPhermons;
pheromones[i][i] = 0;
}
}
if (t == T - 1)
break;
//reset everything
for (int i = 0; i < m; i++) {
ant[i].reset();
}
}
//get the best ant route
double minDistance = Double.MAX_VALUE;
LinkedList<Integer> minRout = new LinkedList<>();
for (Ant ant : ant) {
if (ant.tourDistance < minDistance) {
minDistance = ant.tourDistance;
minRout = ant.citiesVisitedInOrder;
}
}
cout.println(minDistance);
for (int element : minRout)
cout.print(element + " ");
}
private double calculateSum(boolean[] visited, int currentAntsCity) {
//traverse all non-visited cities
double ans = 0.0;
for (int c = 1; c <= n; c++) {
if (!visited[c]) {
ans +=
pow(pheromones[currentAntsCity][c], alpha) *
pow(visibility[currentAntsCity][c], beta);
}
}
return ans;
}
private void initializeParameter() {
m = 2 * n;
T = 4 * m;
city = new City[n + 1];
pheromones = new double[n + 1][n + 1];
distances = new double[n + 1][n + 1];
visibility = new double[n + 1][n + 1];
//read cities coordinates
for (int i = 1; i <= n; i++) {
city[i] = new City(cin.readDouble(), cin.readDouble(), i);
}
//initialize distances
for (int i = 1; i <= n; i++) {
for (int j = i + 1; j <= n; j++) {
distances[i][j] = distances[j][i] = sqrt(pow(city[i].x -
city[j].x, 2.0) + pow(city[i].y -
city[j].y, 2.0));
}
}
//initialize the pheromones
double pheromones0 = 1.0 / (double) n;
for (int i = 1; i <= n; i++) {
Arrays.fill(pheromones[i], pheromones0);
pheromones[i][i] = 0;
}
//initialize the visibility
for (int i = 1; i <= n; i++) {
for (int j = i + 1; j <= n; j++) {
visibility[i][j] = visibility[j][i] = 1.0 / distances[i][j];
}
}
//initialize the ants
ant = new Ant[m];
Random rand = new Random(); //instance of random class for
for (int i = 0; i < m; i++) {
int random_int = rand.nextInt(n) + 1;
ant[i] = new Ant(random_int);
}
}
public static void main(String args[]) {
new test2().run();
}
private void run() {
// cin = new InputReader(System.in);
// cout = new PrintWriter(System.out);
try {
cin = new InputReader(new FileInputStream("input.txt"));
cout = new PrintWriter(new FileOutputStream("output.txt"));
} catch (FileNotFoundException e) {
//System.out.println(e.toString());
}
solve();
cout.close();
}
//just for faster reading from a file
public static class InputReader {
private InputStream stream;
private byte[] buf = new byte[1024];
private int curChar, numChars;
public InputReader(InputStream stream) {
this.stream = stream;
}
public int read() {
if (numChars == -1)
throw new InputMismatchException();
if (curChar >= numChars) {
curChar = 0;
try {
numChars = stream.read(buf);
} catch (IOException e) {
throw new InputMismatchException();
}
if (numChars <= 0)
return -1;
}
return buf[curChar++];
}
public int readInt() {
int c = read();
while (isSpaceChar(c))
c = read();
int sgn = 1;
if (c == '-') {
sgn = -1;
c = read();
}
int res = 0;
do {
if (c < '0' || c > '9')
throw new InputMismatchException();
res *= 10;
res += c - '0';
c = read();
} while (!isSpaceChar(c));
return res * sgn;
}
public double readDouble() {
int c = read();
while (isSpaceChar(c))
c = read();
int sgn = 1;
if (c == '-') {
sgn = -1;
c = read();
}
double res = 0;
while (!isSpaceChar(c) && c != '.') {
if (c == 'e' || c == 'E')
return res * pow(10, readInt());
if (c < '0' || c > '9')
throw new InputMismatchException();
res *= 10;
res += c - '0';
c = read();
}
if (c == '.') {
c = read();
double m = 1;
while (!isSpaceChar(c)) {
if (c == 'e' || c == 'E')
return res * pow(10, readInt());
if (c < '0' || c > '9')
throw new InputMismatchException();
m /= 10;
res += (c - '0') * m;
c = read();
}
}
return res * sgn;
}
private boolean isSpaceChar(int c) {
return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
}
}
}
the test case
10
-15 89
-5 -49
-35 -18
7 49
-95 -68
85 -39
53 -1
69 -99
-74 8
-52 -35
the right answer:
615.11811789868988853
1 9 5 10 3 2 8 6 7 4
my coes's output:
685.2134200307595
5 9 10 3 2 8 6 7 4 1
as you can notice I am not getting the shortest path, I believe that the mistake is somewhere in the constant, and the probability comparing!
the formula I have implemented
and the update formulas
how can I improve the algorithm accuracy? or maybe there's something wrong in my implementation!
I found the solution, Changing the Update functions after each complete tour for all ants, fixed the problem:
#part 1
//the elaboration presses after a complete tour for all ants
for (int i = 1; i <= n; i++) {
for (int j = 1; j <= n; j++) {
pheromones[i][j] *= evaporation;
if (pheromones[i][j] < 1.0 / (double) n)//notice it the phermones can't be less than the starting value`
pheromones[i][j] = 1.0 / (double) n;
pheromones[i][i] = 0;
}
}
#part 2
//update the phermonses
for (int i = 0; i < m; i++) {
for (int j = i + 1; j <= n; j++) {
int from = ant[i].rout[0];
int to = ant[i].rout[n - 1];
pheromones[from][to] += Q / ant[i].tourDistance;
pheromones[to][from] = pheromones[from][to];
}
}
source HERE
strangely enough the algorithm can work without the elaboration presses i.e. #part1.
Anyway here's the complete code with little changes
import java.io.*;
import java.util.*;
import static java.lang.Math.*;
public class test2 {
private InputReader cin;
private PrintWriter cout;
double[][] arr;
double[][] pheromones;
double[][] distances;
double[][] visibility;
static int n;
Ant[] ant;
int m;
int T;
double alpha = 1; // pheromone importance
double beta = 3; // visibility importance
double evaporation = 0.9;
double Q = 40.0;
double pheromones0;
static class Ant {
int whereAmI;
boolean[] visited;
double tourDistance;
private int ctr; //counter for the cites thought which the ant pass
private int[] route;
Ant(int whereAmI) {
this.whereAmI = whereAmI;
reset();
}
void reset() {
ctr = 0;
route = new int[n];
visited = new boolean[n + 1];
visited[whereAmI] = true;
tourDistance = 0;
addCityToTheRoute(whereAmI);
}
void addCityToTheRoute(int cityId) {
route[ctr++] = cityId;
}
}
private void solve() {
n = cin.readInt();
initializeParameter();
double mi = Double.MAX_VALUE;
int[] cityRoute = new int[n];
//the main loop
for (int t = 0; t < T; t++) {
for (int i = 0; i < m; i++) {//for each ant
for (int j = 0; j < n; j++) {//for each city
double highestProbability = 0;
int cityId = 1;
double sumNotiation = calculateSum(ant[i].visited, ant[i].whereAmI);
//traverse all non-visited cities and choose the best
boolean good = false;
for (int c = 1; c <= n; c++) {//remove the equal
if (!ant[i].visited[c]) {
double prop = (pow(pheromones[ant[i].whereAmI][c], alpha) * pow(visibility[ant[i].whereAmI][c], beta))
/ sumNotiation;
if (prop >= highestProbability) {
highestProbability = prop;
cityId = c;
good = true;
}
}
}
if (good) {
ant[i].tourDistance += distances[ant[i].whereAmI][cityId];
ant[i].addCityToTheRoute(cityId);
ant[i].whereAmI = cityId;
ant[i].visited[cityId] = true;
}
}//after n iteration i ant completes a tour
ant[i].tourDistance += distances[ant[i].route[0]][ant[i].route[n - 1]];//add the distance from the last city to the first city
//while k ant finishes its tour take the best ant's route so far
if (ant[i].tourDistance < mi) {
mi = ant[i].tourDistance;
cityRoute = ant[i].route;
}
}
//update
//evaporatePheromones
for (int i = 1; i <= n; i++) {
for (int j = 1; j <= n; j++) {
pheromones[i][j] *= evaporation;
if (pheromones[i][j] < pheromones0)
pheromones[i][j] = pheromones0;
pheromones[i][i] = 0;
}
}
//updatePheromones
for (int i = 0; i < m; i++) {
for (int j = i + 1; j <= n; j++) {
int from = ant[i].route[0];
int to = ant[i].route[n - 1];
pheromones[from][to] += Q / ant[i].tourDistance;
pheromones[to][from] = pheromones[from][to];
}
}
if (t == T - 1)
break;
//reset everything
for (int i = 0; i < m; i++) {
ant[i].reset();
}
}
//print the route with the distance
cout.println(mi);
for (int element : cityRoute)
cout.print(element + " ");
}
private double calculateSum(boolean[] visited, int currentAntsCity) {
//traverse all non-visited cities
double ans = 0.0;
for (int c = 1; c <= n; c++) {
if (!visited[c]) {
ans +=
pow(pheromones[currentAntsCity][c], alpha) *
pow(visibility[currentAntsCity][c], beta);
}
}
return ans;
}
private void initializeParameter() {
m = 20 * n;
T = 20;
pheromones = new double[n + 1][n + 1];
distances = new double[n + 1][n + 1];
visibility = new double[n + 1][n + 1];
//read cities coordinates
arr = new double[n + 1][2];
for (int i = 1; i <= n; i++) {
double x = cin.readDouble();
double y = cin.readDouble();
arr[i][0] = x;
arr[i][1] = y;
}
//initialize distances
for (int i = 1; i <= n; i++) {
for (int j = i + 1; j <= n; j++) {
distances[i][j] = distances[j][i] = sqrt(pow(arr[i][0] -
arr[j][0], 2.0) + pow(arr[i][1] -
arr[j][1], 2.0));
}
}
//initialize the pheromones
pheromones0 = 1.0 / (double) n;
for (int i = 1; i <= n; i++) {
Arrays.fill(pheromones[i], pheromones0);
pheromones[i][i] = 0;
}
//initialize the visibility
for (int i = 1; i <= n; i++) {
for (int j = i + 1; j <= n; j++) {
visibility[i][j] = visibility[j][i] = 1.0 / distances[i][j];
}
}
//initialize the ants
ant = new Ant[m];
Random rand = new Random(); //instance of random class for
for (int i = 0; i < m; i++) {
int random_int = rand.nextInt(n) + 1;
ant[i] = new Ant(random_int);
}
}
public static void main(String args[]) {
new test2().run();
}
private void run() {
// cin = new InputReader(System.in);
// cout = new PrintWriter(System.out);
try {
cin = new InputReader(new FileInputStream("input.txt"));
cout = new PrintWriter(new FileOutputStream("output.txt"));
} catch (FileNotFoundException e) {
//System.out.println(e.toString());
}
solve();
cout.close();
}
//just for faster reading from a file
public static class InputReader {
private InputStream stream;
private byte[] buf = new byte[1024];
private int curChar, numChars;
public InputReader(InputStream stream) {
this.stream = stream;
}
public int read() {
if (numChars == -1)
throw new InputMismatchException();
if (curChar >= numChars) {
curChar = 0;
try {
numChars = stream.read(buf);
} catch (IOException e) {
throw new InputMismatchException();
}
if (numChars <= 0)
return -1;
}
return buf[curChar++];
}
public int readInt() {
int c = read();
while (isSpaceChar(c))
c = read();
int sgn = 1;
if (c == '-') {
sgn = -1;
c = read();
}
int res = 0;
do {
if (c < '0' || c > '9')
throw new InputMismatchException();
res *= 10;
res += c - '0';
c = read();
} while (!isSpaceChar(c));
return res * sgn;
}
public double readDouble() {
int c = read();
while (isSpaceChar(c))
c = read();
int sgn = 1;
if (c == '-') {
sgn = -1;
c = read();
}
double res = 0;
while (!isSpaceChar(c) && c != '.') {
if (c == 'e' || c == 'E')
return res * pow(10, readInt());
if (c < '0' || c > '9')
throw new InputMismatchException();
res *= 10;
res += c - '0';
c = read();
}
if (c == '.') {
c = read();
double m = 1;
while (!isSpaceChar(c)) {
if (c == 'e' || c == 'E')
return res * pow(10, readInt());
if (c < '0' || c > '9')
throw new InputMismatchException();
m /= 10;
res += (c - '0') * m;
c = read();
}
}
return res * sgn;
}
private boolean isSpaceChar(int c) {
return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
}
}
}

Notepad++ to Unix timeshare Transfer issues

So I have a code that appears like it would have perfect formatting in Notepad++, but when I login to my Unix timeshare, open vim, and paste the code into the newly created file, it later has problems compiling. I keep getting "class, interface, or enum expected" errors, however my code appears to have the right amount of brackets and such. I've even tried using Filezilla to transfer my java file in to my unix folder, but I get the same errors. Does anybody else experience problems while transferring code from Notepad++ to Unix? If so, is there a way I can fix this? I've provided my code below; it is meant to find the roots of an entered polynomial using the bisection method:
import java.util.*;
class Roots {
public static int degree;
public static double[] coArrayC;
public static double[] coArrayD;
public static int coeffiNumb;
public static void main( String[] args ){
double resolution = 0.01;
double threshold = 0.001;
double tolerance = 0.0000001;
double rightEndPt;
double leftEndPt;
int polyRootPointer = 0;
int diffRootPointer = 0;
boolean rootAns = false;
Scanner sc = new Scanner(System.in);
System.out.println();
System.out.print("Enter the degree: ");
degree = sc.nextInt();
coeffiNumb = degree + 1;
System.out.print("Enter " + coeffiNumb + " coefficients: ");
double[] coefficients = new double[coeffiNumb];
coArrayC = new double[coeffiNumb];
double[] rootArray = new double[degree];
coArrayD = new double[coeffiNumb];
double[] rootArrayDeriv = new double[degree];
for(int i = 0; i < coeffiNumb; i++) {
coefficients[i] = sc.nextDouble();
}
System.out.print("Enter the lower and upper endpoints, in that order: ");
leftEndPt = sc.nextDouble();
rightEndPt = sc.nextDouble();
diff(coefficients);
for (double i = leftEndPt; i < rightEndPt-resolution; i = i + resolution){
if (isPositive(coArrayD, i) != isPositive(coArrayD, i+resolution) || isPositive(coArrayD, i) == 0) {
rootArrayDeriv[diffRootPointer] = findRoot(coArrayD, i, i+resolution, tolerance);
diffRootPointer++;
}
}
for (int i = 0; i < rootArrayDeriv.length; i++) {
double tempVal;
tempVal = poly(coefficients, rootArrayDeriv[i]);
tempVal = Math.abs(tempVal);
if (tempVal < threshold) {
rootArray[polyRootPointer] = rootArrayDeriv[i];
polyRootPointer++;
rootAns = true;
}
}
for (double i = leftEndPt; i < rightEndPt-resolution; i = i + resolution){
if (isPositive(coefficients, i) != isPositive(coefficients, i+resolution) || isPositive(coefficients, i) == 0) {
rootArray[polyRootPointer] = findRoot(coefficients, i, i+resolution, tolerance);
polyRootPointer++;
rootAns = true;
}
}
Arrays.sort(rootArray);
if (rootAns == false) {
System.out.println("Sorry - no roots were found at that particular interval.");
}
}
} else {
for (int i = 0; i < rootArray.length; i++) {
if (rootArray[i] != 0.0) {
System.out.printf("Root found at %.5f%n", Arrays.sort(rootArray));
}
}
static double poly(double[] C, double x){
double polySum = 0;
coArrayC[0] = C[0];
for (int i = 1; i < coArrayC.length; i++){
coArrayC[i] = C[i]*(Math.pow(x, i));
}
for (int i = 0; i < coArrayC.length; i++){
polySum = polySum + coArrayC[i];
}
return(polySum);
}
static double[] diff(double[] C){
for (int i = 0; i < degree; i++){
coArrayD[i] = (i+1)*C[i+1];
}
return(coArrayD);
}
static double findRoot(double[] C, double a, double b, double tolerance){
double root = 0.0 , residual;
while ( Math.abs(b - a) > tolerance ) {
root = (a + b) / 2.0;
residual = poly(C, root);
if (poly(C, a) > 0 && poly(C, b) < 0) {
if (residual > 0)
a = root;
else
b = root;
} else if (poly(C, a) < 0 && poly(C, b) > 0) {
if (residual > 0)
b = root;
else
a = root;
}
}
return(root);
}
static int isPositive(double[] C, double a){
double endpointTempA;
endpointTempA = poly(C, a);
if (endpointTempA < 0) {
return(1);
} else if (endpointTempA > 0) {
return(2);
} else {
return(0);
}
}
}

Adding binary numbers

Does anyone know how to add 2 binary numbers, entered as binary, in Java?
For example, 1010 + 10 = 1100.
Use Integer.parseInt(String, int radix).
public static String addBinary(){
// The two input Strings, containing the binary representation of the two values:
String input0 = "1010";
String input1 = "10";
// Use as radix 2 because it's binary
int number0 = Integer.parseInt(input0, 2);
int number1 = Integer.parseInt(input1, 2);
int sum = number0 + number1;
return Integer.toBinaryString(sum); //returns the answer as a binary value;
}
To dive into fundamentals:
public static String binaryAddition(String s1, String s2) {
if (s1 == null || s2 == null) return "";
int first = s1.length() - 1;
int second = s2.length() - 1;
StringBuilder sb = new StringBuilder();
int carry = 0;
while (first >= 0 || second >= 0) {
int sum = carry;
if (first >= 0) {
sum += s1.charAt(first) - '0';
first--;
}
if (second >= 0) {
sum += s2.charAt(second) - '0';
second--;
}
carry = sum >> 1;
sum = sum & 1;
sb.append(sum == 0 ? '0' : '1');
}
if (carry > 0)
sb.append('1');
sb.reverse();
return String.valueOf(sb);
}
Martijn is absolutely correct, to piggyback and complete the answer
Integer.toBinaryString(sum);
would give your output in binary as per the OP question.
You can just put 0b in front of the binary number to specify that it is binary.
For this example, you can simply do:
Integer.toString(0b1010 + 0b10, 2);
This will add the two in binary, and Integer.toString() with 2 as the second parameter converts it back to binary.
The original solution by Martijn will not work for large binary numbers. The below code can be used to overcome that.
public String addBinary(String s1, String s2) {
StringBuilder sb = new StringBuilder();
int i = s1.length() - 1, j = s2.length() -1, carry = 0;
while (i >= 0 || j >= 0) {
int sum = carry;
if (j >= 0) sum += s2.charAt(j--) - '0';
if (i >= 0) sum += s1.charAt(i--) - '0';
sb.append(sum % 2);
carry = sum / 2;
}
if (carry != 0) sb.append(carry);
return sb.reverse().toString();
}
public class BinaryArithmetic {
/*-------------------------- add ------------------------------------------------------------*/
static String add(double a, double b) {
System.out.println(a + "first val :" + b);
int a1 = (int) a;
int b1 = (int) b;
String s1 = Integer.toString(a1);
String s2 = Integer.toString(b1);
int number0 = Integer.parseInt(s1, 2);
int number1 = Integer.parseInt(s2, 2);
int sum = number0 + number1;
String s3 = Integer.toBinaryString(sum);
return s3;
}
/*-------------------------------multiply-------------------------------------------------------*/
static String multiply(double a, double b) {
System.out.println(a + "first val :" + b);
int a1 = (int) a;
int b1 = (int) b;
String s1 = Integer.toString(a1);
String s2 = Integer.toString(b1);
int number0 = Integer.parseInt(s1, 2);
int number1 = Integer.parseInt(s2, 2);
int sum = number0 * number1;
String s3 = Integer.toBinaryString(sum);
return s3;
}
/*----------------------------------------substraction----------------------------------------------*/
static String sub(double a, double b) {
System.out.println(a + "first val :" + b);
int a1 = (int) a;
int b1 = (int) b;
String s1 = Integer.toString(a1);
String s2 = Integer.toString(b1);
int number0 = Integer.parseInt(s1, 2);
int number1 = Integer.parseInt(s2, 2);
int sum = number0 - number1;
String s3 = Integer.toBinaryString(sum);
return s3;
}
/*--------------------------------------division------------------------------------------------*/
static String div(double a, double b) {
System.out.println(a + "first val :" + b);
int a1 = (int) a;
int b1 = (int) b;
String s1 = Integer.toString(a1);
String s2 = Integer.toString(b1);
int number0 = Integer.parseInt(s1, 2);
int number1 = Integer.parseInt(s2, 2);
int sum = number0 / number1;
String s3 = Integer.toBinaryString(sum);
return s3;
}
}
Another interesting but long approach is to convert each of the two numbers to decimal, adding the decimal numbers and converting the answer obtained back to binary!
Java solution
static String addBinary(String a, String b) {
int lenA = a.length();
int lenB = b.length();
int i = 0;
StringBuilder sb = new StringBuilder();
int rem = Math.abs(lenA-lenB);
while(rem >0){
sb.append('0');
rem--;
}
if(lenA > lenB){
sb.append(b);
b = sb.toString();
}else{
sb.append(a);
a = sb.toString();
}
sb = new StringBuilder();
char carry = '0';
i = a.length();
while(i > 0){
if(a.charAt(i-1) == b.charAt(i-1)){
sb.append(carry);
if(a.charAt(i-1) == '1'){
carry = '1';
}else{
carry = '0';
}
}else{
if(carry == '1'){
sb.append('0');
carry = '1';
}else{
carry = '0';
sb.append('1');
}
}
i--;
}
if(carry == '1'){
sb.append(carry);
}
sb.reverse();
return sb.toString();
}
public String addBinary(String a, String b) {
int carry = 0;
StringBuilder sb = new StringBuilder();
for(int i = a.length() - 1, j = b.length() - 1;i >= 0 || j >= 0;i--,j--){
int sum = carry + (i >= 0 ? a.charAt(i) - '0':0) + (j >= 0 ? b.charAt(j) - '0' : 0);
sb.append(sum%2);
carry =sum / 2;
}
if(carry > 0) sb.append(carry);
sb.reverse();
return sb.toString();
}
I've actually managed to find a solution to this question without using the stringbuilder() function. Check this out:
public void BinaryAddition(String s1,String s2)
{
int l1=s1.length();int c1=l1;
int l2=s2.length();int c2=l2;
int max=(int)Math.max(l1,l2);
int arr1[]=new int[max];
int arr2[]=new int[max];
int sum[]=new int[max+1];
for(int i=(arr1.length-1);i>=(max-l1);i--)
{
arr1[i]=(int)(s1.charAt(c1-1)-48);
c1--;
}
for(int i=(arr2.length-1);i>=(max-l2);i--)
{
arr2[i]=(int)(s2.charAt(c2-1)-48);
c2--;
}
for(int i=(sum.length-1);i>=1;i--)
{
sum[i]+=arr1[i-1]+arr2[i-1];
if(sum[i]==2)
{
sum[i]=0;
sum[i-1]=1;
}
else if(sum[i]==3)
{
sum[i]=1;
sum[i-1]=1;
}
}
int c=0;
for(int i=0;i<sum.length;i++)
{
System.out.print(sum[i]);
}
}
The idea is same as discussed in few of the answers, but this one is a much shorter and easier to understand solution (steps are commented).
// Handles numbers which are way bigger.
public String addBinary(String a, String b) {
StringBuilder sb = new StringBuilder();
int i = a.length() - 1;
int j = b.length() -1;
int carry = 0;
while (i >= 0 || j >= 0) {
int sum = carry;
if (j >= 0) { sum += b.charAt(j--) - '0' };
if (i >= 0) { sum += a.charAt(i--) - '0' };
// Added number can be only 0 or 1
sb.append(sum % 2);
// Get the carry.
carry = sum / 2;
}
if (carry != 0) { sb.append(carry); }
// First reverse and then return.
return sb.reverse().toString();
}
i tried to make it simple this was sth i had to deal with with my cryptography prj its not efficient but i hope it
public String binarysum(String a, String b){
int carry=0;
int maxim;
int minim;
maxim=Math.max(a.length(),b.length());
minim=Math.min(a.length(),b.length());
char smin[]=new char[minim];
char smax[]=new char[maxim];
if(a.length()==minim){
for(int i=0;i<smin.length;i++){
smin[i]=a.charAt(i);
}
for(int i=0;i<smax.length;i++){
smax[i]=b.charAt(i);
}
}
else{
for(int i=0;i<smin.length;i++){
smin[i]=b.charAt(i);
}
for(int i=0;i<smax.length;i++){
smax[i]=a.charAt(i);
}
}
char[]sum=new char[maxim];
char[] st=new char[maxim];
for(int i=0;i<st.length;i++){
st[i]='0';
}
int k=st.length-1;
for(int i=smin.length-1;i>-1;i--){
st[k]=smin[i];
k--;
}
// *************************** sum begins here
for(int i=maxim-1;i>-1;i--){
char x= smax[i];
char y= st[i];
if(x==y && x=='0'){
if(carry==0)
sum[i]='0';
else if(carry==1){
sum[i]='1';
carry=0;
}
}
else if(x==y && x=='1'){
if(carry==0){
sum[i]='0';
carry=1;
}
else if(carry==1){
sum[i]='1';
carry=1;
}
}
else if(x!=y){
if(carry==0){
sum[i]='1';
}
else if(carry==1){
sum[i]='0';
carry=1;
}
} }
String s=new String(sum);
return s;
}
class Sum{
public int number;
public int carry;
Sum(int number, int carry){
this.number = number;
this.carry = carry;
}
}
public String addBinary(String a, String b) {
int lengthOfA = a.length();
int lengthOfB = b.length();
if(lengthOfA > lengthOfB){
for(int i=0; i<(lengthOfA - lengthOfB); i++){
b="0"+b;
}
}
else{
for(int i=0; i<(lengthOfB - lengthOfA); i++){
a="0"+a;
}
}
String result = "";
Sum s = new Sum(0,0);
for(int i=a.length()-1; i>=0; i--){
s = addNumber(Character.getNumericValue(a.charAt(i)), Character.getNumericValue(b.charAt(i)), s.carry);
result = result + Integer.toString(s.number);
}
if(s.carry == 1) { result += s.carry ;}
return new StringBuilder(result).reverse().toString();
}
Sum addNumber(int number1, int number2, int carry){
Sum sum = new Sum(0,0);
sum.number = number1 ^ number2 ^ carry;
sum.carry = (number1 & number2) | (number2 & carry) | (number1 & carry);
return sum;
}
import java.util.*;
public class BitAddition {
/**
* #param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner sc = new Scanner(System.in);
int len = sc.nextInt();
int[] arr1 = new int[len];
int[] arr2 = new int[len];
int[] sum = new int[len+1];
Arrays.fill(sum, 0);
for(int i=0;i<len;i++){
arr1[i] =sc.nextInt();
}
for(int i=0;i<len;i++){
arr2[i] =sc.nextInt();
}
for(int i=len-1;i>=0;i--){
if(sum[i+1] == 0){
if(arr1[i]!=arr2[i]){
sum[i+1] = 1;
}
else if(arr1[i] ==1 && arr2[i] == 1){
sum[i+1] =0 ;
sum[i] = 1;
}
}
else{
if((arr1[i]!=arr2[i])){
sum[i+1] = 0;
sum[i] = 1;
}
else if(arr1[i] == 1){
sum[i+1] = 1;
sum[i] = 1;
}
}
}
for(int i=0;i<=len;i++){
System.out.print(sum[i]);
}
}
}
One of the simple ways is as:
convert the two strings to char[] array and set carry=0.
set the smallest array length in for loop
start for loop from the last index and decrement it
check 4 conditions(0+0=0, 0+1=1, 1+0=1, 1+1=10(carry=1)) for binary addition for each element in both the arrays and reset the carry accordingly.
append the addition in stringbuffer
append rest of the elements from max size array to stringbuffer but check consider carry while appending
print stringbuffer in reverse order for the answer.
//The java code is as
static String binaryAdd(String a, String b){
int len = 0;
int size = 0;
char[] c1 = a.toCharArray();
char[] c2 = b.toCharArray();
char[] max;
if(c1.length > c2.length){
len = c2.length;
size = c1.length;
max = c1;
}
else
{
len = c1.length;
size = c2.length;
max = c2;
}
StringBuilder sb = new StringBuilder();
int carry = 0;
int p = c1.length - 1;
int q = c2.length - 1;
for(int i=len-1; i>=0; i--){
if(c1[p] == '0' && c2[q] == '0'){
if(carry == 0){
sb.append(0);
carry = 0;
}
else{
sb.append(1);
carry = 0;
}
}
if((c1[p] == '0' && c2[q] == '1') || (c1[p] == '1' && c2[q] == '0')){
if(carry == 0){
sb.append(1);
carry = 0;
}
else{
sb.append(0);
carry = 1;
}
}
if((c1[p] == '1' && c2[q] == '1')){
if(carry == 0){
sb.append(0);
carry = 1;
}
else{
sb.append(1);
carry = 1;
}
}
p--;
q--;
}
for(int j = size-len-1; j>=0; j--){
if(max[j] == '0'){
if(carry == 0){
sb.append(0);
carry = 0;
}
else{
sb.append(1);
carry = 0;
}
}
if(max[j] == '1'){
if(carry == 0){
sb.append(1);
carry = 0;
}
else{
sb.append(0);
carry = 1;
}
}
}
if(carry == 1)
sb.append(1);
return sb.reverse().toString();
}
import java.io.;
import java.util.;
public class adtbin {
static Scanner sc=new Scanner(System.in);
public void fun(int n1) {
int i=0;
int sum[]=new int[20];
while(n1>0) {
sum[i]=n1%2; n1=n1/2; i++;
}
for(int a=i-1;a>=0;a--) {
System.out.print(sum[a]);
}
}
public static void main() {
int m,n,add;
adtbin ob=new adtbin();
System.out.println("enter the value of m and n");
m=sc.nextInt();
n=sc.nextInt();
add=m+n;
ob.fun(add);
}
}
you can write your own One.
long a =100011111111L;
long b =1000001111L;
int carry = 0 ;
long result = 0;
long multiplicity = 1;
while(a!=0 || b!=0 || carry ==1){
if(a%10==1){
if(b%10==1){
result+= (carry*multiplicity);
carry = 1;
}else if(carry == 1){
carry = 1;
}else{
result += multiplicity;
}
}else if (b%10 == 1){
if(carry == 1){
carry = 1;
}else {
result += multiplicity;
}
}else {
result += (carry*multiplicity);
carry = 0;
}
a/=10;
b/=10;
multiplicity *= 10;
}
System.out.print(result);
it works just by numbers , no need string , no need SubString and ...
package Assignment19thDec;
import java.util.Scanner;
public class addTwoBinaryNumbers {
private static Scanner sc;
public static void main(String[] args) {
sc = new Scanner(System.in);
System.out.println("Enter 1st Binary Number");
int number1=sc.nextInt();
int reminder1=0;
int number2=sc.nextInt();
int reminder2=0;
int carry=0;
double sumResult=0 ;int add = 0
;
int n;
int power=0;
while (number1>0 || number2>0) {
/*System.out.println(number1 + " " +number2);*/
reminder1=number1%10;
number1=number1/10;
reminder2=number2%10;
number2=number2/10;
/*System.out.println(reminder1 +" "+ reminder2);*/
if(reminder1>1 || reminder2>1 ) {
System.out.println("not a binary number");
System.exit(0);
}
n=reminder1+reminder2+carry;
switch(n) {
case 0:
add=0; carry=0;
break;
case 1: add=1; carry=0;
break;
case 2: add=0; carry=1;
break;
case 3: add=1;carry=1;
break;
default: System.out.println("not a binary number ");
}
sumResult=add*(Math.pow(10, power))+sumResult;
power++;
}
sumResult=carry*(Math.pow(10, power))+sumResult;
System.out.println("\n"+(int)sumResult);
}
}
Try this, tested with binary and decimal and its self explanatory
public String add(String s1, String s2, int radix){
int s1Length = s1.length();
int s2Length = s2.length();
int reminder = 0;
int carry = 0;
StringBuilder result = new StringBuilder();
int i = s1Length -1;
int j = s2Length -1;
while (i >=0 && j>=0) {
int operand1 = Integer.valueOf(s1.charAt(i)+"");
int operand2 = Integer.valueOf(s2.charAt(j)+"");
reminder = (operand1+operand2+carry) % radix;
carry = (operand1+operand2+carry) / radix;
result.append(reminder);
i--;j--;
}
while(i>=0){
int operand1 = Integer.valueOf(s1.charAt(i)+"");
reminder = (operand1+carry) % radix;
carry = (operand1+carry) / radix;
result.append(reminder);
i--;
}
while(j>=0){
int operand1 = Integer.valueOf(s2.charAt(j)+"");
reminder = (operand1+carry) % radix;
carry = (operand1+carry) / radix;
result.append(reminder);
j--;
}
return result.reverse().toString();
}
}
static int addBinaryNumbers(String a, String b) {
int firstToDecimal = 0;
int secondToDecimal = 0;
for (int i = a.length() - 1, count = 0; i >= 0; i--, count++) {
firstToDecimal += (Math.pow(2, count) * Integer.parseInt(String.valueOf(a.toCharArray()[i])));
}
for (int i = b.length() - 1, count = 0; i >= 0; i--, count++) {
secondToDecimal += (Math.pow(2, count) * Integer.parseInt(String.valueOf(b.toCharArray()[i])));
}
return firstToDecimal + secondToDecimal;
}
public static void main(String[] args) {
System.out.println(addBinaryNumbers("101", "110"));
}
here's a python version that
def binAdd(s1, s2):
if not s1 or not s2:
return ''
maxlen = max(len(s1), len(s2))
s1 = s1.zfill(maxlen)
s2 = s2.zfill(maxlen)
result = ''
carry = 0
i = maxlen - 1
while(i >= 0):
s = int(s1[i]) + int(s2[i])
if s == 2: #1+1
if carry == 0:
carry = 1
result = "%s%s" % (result, '0')
else:
result = "%s%s" % (result, '1')
elif s == 1: # 1+0
if carry == 1:
result = "%s%s" % (result, '0')
else:
result = "%s%s" % (result, '1')
else: # 0+0
if carry == 1:
result = "%s%s" % (result, '1')
carry = 0
else:
result = "%s%s" % (result, '0')
i = i - 1;
if carry>0:
result = "%s%s" % (result, '1')
return result[::-1]
import java.util.Scanner;
{
public static void main(String[] args)
{
String b1,b2;
Scanner sc= new Scanner(System.in);
System.out.println("Enter 1st binary no. : ") ;
b1=sc.next();
System.out.println("Enter 2nd binary no. : ") ;
b2=sc.next();
int num1=Integer.parseInt(b1,2);
int num2=Integer.parseInt(b2,2);
int sum=num1+num2;
System.out.println("Additon is : "+Integer.toBinaryString(sum));
}
}

Categories