Randomly getting null in elements of array - java

when I create an array of Monomial by using Polynomial constructor,so sometimes
I get null object instead of Monomial object and sometimes I get the actual Monomial.
I don't understand why
I debug the code and in Polynomial constructor I construct the specific objects but when I return to the main method so sometimes I get the specific array of Monomial and sometimes I get a null in the a array.
TestPolynomials.java
public class TestPolynomials
{
public static void main(String[] args)
{
// 13b^2x^3z
Monomial m1 = new Monomial(13);
m1.setDegree('b', 2);
m1.setDegree('x', 3);
m1.setDegree('z', 1);
// 15
Monomial m2 = new Monomial(15);
Polynomial p1 = new Polynomial(new Monomial[] { m1, m2 });
}
}
Monomial.java
public class Monomial
{
private int coefficient;
private int[] var;
public Monomial(int coefficient)
{
this.coefficient = coefficient;
this.var = new int[26];
}
public int getCoefficient()
{
return coefficient;
}
public void setCoefficient(int coefficient)
{
this.coefficient = coefficient;
}
public int getDegree(char variable)
{
return var[variable - 'a'];
}
public void setDegree(char variable, int degree)
{
this.var[variable - 'a'] = degree;
}
public Monomial getCopy()
{
Monomial monom = new Monomial(this.coefficient);
for (char ch = 'a'; ch <= 'z'; ch++)
{
if (this.getDegree(ch) > 0)
monom.setDegree(ch, this.getDegree(ch));
}
return monom;
}
public String toString()
{
String monom = "";
monom += Integer.toString(this.getCoefficient());
for (char ch = 'a'; ch <= 'z'; ch++)
{
if (this.getDegree(ch) > 0)
{
monom += ch;
if (this.getDegree(ch) > 1)
{
monom += "^";
monom += Integer.toString(this.getDegree(ch));
}
}
}
return monom;
}
}
Polynomial.java
public class Polynomial
{
private Monomial[] monomials;
public Polynomial(Monomial[] monomials)
{
this.monomials = new Monomial[monomials.length];
for (int i = 0; i < monomials.length; i++)
{
this.monomials[i] = monomials[i].getCopy();
}
}
public String toString()
{
String str = "";
for (int i = 0; i < this.getMonomialCount(); i++)
{
str += this.getMonomial(i).toString();
str += "+";
}
return str;
}
}
I construct m1 and m2 and I try to construct p1.
sometimes I get this: [13b^2x^3z, 15]and sometimes I get this:[null, 30]
Why?
Thanks.
========================================================================
edit:This is my full code,when I run it I get this in console
m1 = 13b^2x^3z
m2 = 15
m3 = -4b^2x^3z
m4 = 10b^3x^4z^2
13b^2x^3z does not have the same degrees as 15
13b^2x^3z has the same degrees as -4b^2x^3z
Exception in thread "main" java.lang.NullPointerException
at Polynomial.toString(Polynomial.java:98)
at java.lang.String.valueOf(Unknown Source)
at java.lang.StringBuilder.append(Unknown Source)
at TestPolynomials.main(TestPolynomials.java:44)
TestPolynomials.java
public class TestPolynomials
{
private static String tempstr = ""; // For printing results;
public static void main(String[] args)
{
// 13b^2x^3z
Monomial m1 = new Monomial(13);
m1.setDegree('b', 2);
m1.setDegree('x', 3);
m1.setDegree('z', 1);
System.out.println("m1 = " + m1);
// 15
Monomial m2 = new Monomial(15);
System.out.println("m2 = " + m2);
// -4b^2x^3z
Monomial m3 = new Monomial(-4);
m3.setDegree('b', 2);
m3.setDegree('x', 3);
m3.setDegree('z', 1);
System.out.println("m3 = " + m3);
Monomial m4 = new Monomial(10);
m4.setDegree('b', 3);
m4.setDegree('x', 4);
m4.setDegree('z', 2);
System.out.println("m4 = " + m4);
if (m1.hasSameDegrees(m2))
tempstr = " has";
else
tempstr = " does not have";
System.out.println(m1 + tempstr + " the same degrees as " + m2);
if (m1.hasSameDegrees(m3))
tempstr = " has";
else
tempstr = " does not have";
System.out.println(m1 + tempstr + " the same degrees as " + m3);
Polynomial p1 = new Polynomial(new Monomial[] { m1, m2 });
Polynomial p2 = new Polynomial(new Monomial[] { m3 });
Polynomial p3 = p1.add(p2);
System.out.println("p1 = " + p1); // should be 13b^2x^3z+15
System.out.println("p2 = " + p2); // should be -4b^2x^3z
System.out.println("p3 = " + p3); // should be 13b^2x^3z+15-4b^2x^3z up to reordering the monomials
System.out.println("-p3 = " + p3.inverse()); // should be -13b^2x^3z-15+4b^2x^3z up to reordering the monomials
System.out.println("p4 = p3 + p2");
Polynomial p4 = p3.add(p2);
int[] assignment = { 0, 1, 6, 4, 3, 0, 0, 2, 3, 5, 2, 6, 3, 8, 7, 0, 0, 4, 2, 6, 0, 4, 1, 5, 1, 9 };
System.out.println("p4 value = " + p4.computeValue(assignment) + " --- before normalization");
p4.normalize();
System.out.println("p4 = " + p4);
System.out.println("p4 value = " + p4.computeValue(assignment) + " --- after normalization");
Polynomial p5 = new Polynomial(new Monomial[] { m1, m2, m3, m4, m1, m2, m3, m4, m4 });
System.out.println("p5 items are m1,m2,m3,m4,m1,m2,m3,m4,m4");
System.out.println("p5 = " + p5);
Monomial m5 = new Monomial(0);
m5.setDegree('z', 1);
Polynomial p6 = new Polynomial(new Monomial[] { m5 });
System.out.println("p6 = " + p6);
Polynomial p7 = new Polynomial(new Monomial[] {});
System.out.println("p7 = " + p7);
}
}
Monomial.java
public class Monomial
{
private int coefficient;
private int[] var;
public Monomial(int coefficient)
{
this.coefficient = coefficient;
this.var = new int[26];
}
public int getCoefficient()
{
return coefficient;
}
public void setCoefficient(int coefficient)
{
this.coefficient = coefficient;
}
public int getDegree(char variable)
{
return var[variable - 'a'];
}
public void setDegree(char variable, int degree)
{
this.var[variable - 'a'] = degree;
}
public boolean hasSameDegrees(Monomial other)
{
for (char ch = 'a'; ch <= 'z'; ch++)
{
if (!(this.getDegree(ch) == other.getDegree(ch)))
return false;
}
return true;
}
public Monomial getCopy()
{
Monomial monom = new Monomial(this.coefficient);
for (char ch = 'a'; ch <= 'z'; ch++)
{
if (this.getDegree(ch) > 0)
monom.setDegree(ch, this.getDegree(ch));
}
return monom;
}
public String toString()
{
String monom = "";
monom += Integer.toString(this.getCoefficient());
for (char ch = 'a'; ch <= 'z'; ch++)
{
if (this.getDegree(ch) > 0)
{
monom += ch;
if (this.getDegree(ch) > 1)
{
monom += "^";
monom += Integer.toString(this.getDegree(ch));
}
}
}
return monom;
}
}
Polynomial.java
import java.lang.Math;
public class Polynomial
{
private Monomial[] monomials;
public Polynomial(Monomial[] monomials)
{
this.monomials = new Monomial[monomials.length];
for (int i = 0; i < monomials.length; i++)
{
this.monomials[i] = monomials[i].getCopy();
}
}
public int getMonomialCount()
{
return this.monomials.length;
}
public Monomial getMonomial(int index)
{
if (index <= this.getMonomialCount())
return this.monomials[index];
return null;
}
public Polynomial inverse()
{
Monomial[] inverse = new Monomial[this.getMonomialCount()];
for (int i = 0; i < inverse.length; i++)
{
inverse[i] = this.monomials[i].getCopy();
inverse[i].setCoefficient(inverse[i].getCoefficient() * -1);
}
return new Polynomial(inverse);
}
public Polynomial add(Polynomial other)
{
Monomial[] add = new Monomial[this.getMonomialCount() + other.getMonomialCount()];
for (int i = 0; i < other.getMonomialCount(); i++)
{
add[i] = other.getMonomial(i).getCopy();
}
for (int i = other.getMonomialCount(); i < add.length; i++)
{
add[i] = this.monomials[i - other.getMonomialCount()].getCopy();
}
return new Polynomial(add);
}
public int computeValue(int[] assignment)
{
int result = 1, sum = 0;
for (int i = 0; i < this.getMonomialCount(); i++)
{
for (char ch = 'a'; ch <= 'z'; ch++)
{
if (this.getMonomial(i).getDegree(ch) > 0)
result *= (int) Math.pow((double) assignment[i], (double) this.getMonomial(i).getDegree(ch));
}
result *= this.getMonomial(i).getCoefficient();
sum += result;
result = 1;
}
return sum;
}
public void normalize()
{
Monomial[] normalize = new Monomial[this.getMonomialCount()];
for (int i = 0; i < this.getMonomialCount(); i++)
{
for (int j = 1; j < this.getMonomialCount(); j++)
{
if (this.getMonomial(i).hasSameDegrees(this.getMonomial(j)))
{
normalize[i] = new Monomial(this.getMonomial(i).getCoefficient() + this.getMonomial(j).getCoefficient());
for (char ch = 'a'; ch <= 'z'; ch++)
{
if (this.getMonomial(i).getDegree(ch) > 0)
normalize[i].setDegree(ch, this.getMonomial(i).getDegree(ch));
}
this.monomials[i] = null;
}
}
}
this.monomials = normalize;
}
public String toString()
{
normalize();
String str = "";
for (int i = 0; i < this.getMonomialCount(); i++)
{
str += this.getMonomial(i).toString();
str += "+";
}
return str;
}
}
Why??

Related

Java Decode RLE string

Example if i have an input like:
H9e3e2l5o
the output have to be:
Heeeeeeeeeeeellooooo
This is the code that I wrote so far:
public class RLE {
public static String decode(String st) {
char[] stArr = st.toCharArray();
char lastseen = 0;
StringBuilder sb = new StringBuilder();
for (char s : stArr) {
if (!Character.isDigit(s)) {
lastseen = s;
sb.append(s);
} else {
int n = Integer.parseInt(String.valueOf(s));
for (int i = 0; i < n - 1; i++) {
sb.append(lastseen);
}
}
}
return sb.toString();
}
Results in:
'H9e3e2l5o' -> HHHHHHHHHeeeeelllllo
I'm assuming generic variant, here is corrected version:
public static String decode(final String st) {
final StringBuilder sb = new StringBuilder();
final char[] chars = st.toCharArray();
int i = 0;
while (i < chars.length) {
int repeat = 0;
while ((i < chars.length) && Character.isDigit(chars[i])) {
repeat = repeat * 10 + chars[i++] - '0';
}
final StringBuilder s = new StringBuilder();
while ((i < chars.length) && !Character.isDigit(chars[i])) {
s.append(chars[i++]);
}
if (repeat > 0) {
for (int j = 0; j < repeat; j++) {
sb.append(s.toString());
}
} else {
sb.append(s.toString());
}
}
return sb.toString();
}
#Test
public void test() {
Assert.assertEquals("abb", decode("1a2b"));
Assert.assertEquals("aaaaaaaaaa", decode("10a"));
Assert.assertEquals("baaaaaaaaaa", decode("b10a"));
Assert.assertEquals("abab", decode("2ab"));
Assert.assertEquals("Heeeeeeeeeeeellooooo", decode("H9e3e2l5o"));
}

I can't open the jar file of the project

I have a project that I need to have its jar file , but it doesn't open , can anyone help me please, I need it as soon as possible for my university . And here is the whole code :
package huffmanproject;
import java.util.ArrayList;
import java.util.PriorityQueue;
public class huffmanproject {
public static class HuffNode implements Comparable<HuffNode> {
public int value;
public int weight;
public HuffNode leftTree;
public HuffNode rightTree;
public HuffNode parent;
public HuffNode() {
parent = null;
}
public HuffNode( int v, int w, HuffNode lTree, HuffNode rTree, HuffNode par ) {
value = v;
weight = w;
leftTree = lTree;
rightTree = rTree;
parent = par;
}
#Override
public int compareTo(HuffNode rhs) {
return weight - rhs.weight;
}
#Override
public String toString() {
String str = "";
str += this.value;
return str;
}
}
public static class HuffTree {
private int size = 0;
private HuffNode root = new HuffNode();
private PriorityQueue<HuffNode> huffQueue = new PriorityQueue();
public ArrayList<String> pathTable = new ArrayList();
public ArrayList<Character> valueTable = new ArrayList();
public HuffTree(int[] freq, char[] code) {
this.size = freq.length;
if (freq.length != code.length) {
throw new UnsupportedOperationException("Error: Character and code length mismatch.");
}
for (int i = 0; i < this.size; i++) {
huffQueue.offer(new HuffNode(code[i], freq[i], null, null, null));
}
createTree();
createTable(this.root, "");
}
private void createTree() {
while (huffQueue.size() > 1) {
HuffNode tempL = huffQueue.poll();
HuffNode tempR = huffQueue.poll();
HuffNode parent = new HuffNode(0, tempL.weight+tempR.weight, tempL, tempR, null);
tempL.parent = parent;
tempR.parent = parent;
huffQueue.offer(parent);
this.size++;
}
this.root = huffQueue.peek();
}
private void createTable(HuffNode curr, String str) {
if (curr == null) return;
if (curr.leftTree == null && curr.rightTree == null) {
char tempChar;
if (curr.value == 32)
tempChar = ' ';
if (curr.value == 10)
tempChar = 'n';
else
tempChar = (char)curr.value;
this.valueTable.add(tempChar);
this.pathTable.add(str);
}
str += "0";
createTable(curr.leftTree, str);
str = str.substring(0, str.length()-1);
str += "1";
createTable(curr.rightTree, str);
}
String tacks = "";
public void getTree(HuffNode curr) {
if (curr == null) return;
if (curr.leftTree == null && curr.rightTree == null) {
switch (curr.value) {
case 32:
System.out.println(tacks + curr.weight + ": sp");
break;
case 10:
System.out.println(tacks + curr.weight + ": nl");
break;
default:
System.out.println(tacks + curr.weight + ": " + (char)curr.value);
break;
}
}
else
System.out.println(tacks + curr.weight);
tacks += "- ";
getTree(curr.leftTree);
getTree(curr.rightTree);
tacks = tacks.substring(0, tacks.length()-2);
}
public int getSize() { return this.size; }
public String encode(String input){
String str = "";
for (int x = 0; x < input.length(); x++) {
for (int i = 0; i < valueTable.size(); i++) {
if (valueTable.get(i) == input.charAt(x))
str += pathTable.get(i);
}
}
return str;
}
public String decode(String bits) {
String decodedStr = "";
for (int i = 0; i < bits.length(); i++) {
if (!getChar(bits.substring(0, i+1)).equals("")) {
decodedStr += getChar(bits.substring(0, i+1));
bits = bits.substring(i+1);
i = 0;
}
}
return decodedStr;
}
private String getChar(String bits) {
String character = "";
for (int i = 0; i < pathTable.size(); i++) {
if (pathTable.get(i).equals(bits))
character = valueTable.get(i).toString();
}
return character;
}
}
public static void main(String[] args) {
// for example assume that we have these letters with these different frequencies like below:
int freq[] = {10, 15, 12, 3, 4, 13, 1};
char code[] = {'a', 'e', 'i', 's', 't', ' ', '\n'};
HuffTree hTree = new HuffTree(freq, code);
System.out.println("Display Tree:");
HuffNode curr = hTree.root;
hTree.getTree(curr);
System.out.println("");
// and we want to build the huffman tree of the word sea :
System.out.println("Encode 'sea': " + hTree.encode("sea") +"\n");
System.out.println("Decode '" + hTree.encode("sea") + "': " + hTree.decode(hTree.encode("tea")));
}
}
If it's simply not compiling into a jar file, try the following command in command prompt or terminal.
jar cf jar-file input-file(s)
From Oracle: Creating jar File
To open command prompt, use WIN+R to open the run box, type cmd, and press enter.
navigate to the directory of your java file:
cd C:\Path\to\my\java\file\HuffNode.java
run the command:
jar cf HuffNode.jar HuffNode.java
If you have multiple .java files:
jar cf HuffNode.jar File1.java File2.java File3.java

How to show all combinations of IP address that can be created from a string of numbers?

I need to format the input string into IP address format, so I have the following code;however,the numbers are fixed and I am not sure how to generated different values for a single input.
Other constraints would be to make sure no group of numbers is more than 255, but in this case I just want to put them in four separate groups and each group must have 1 to 3 members.
Vimal's question: From provided string 19216801, I think you cant identify exact ip. It can be 192.168.0.1 or 19.216.80.1 or any other combination.
Answer: I am not looking for any specific IP I just need to show all the possible combinations.
Sample formats
Some of the combinations would be as following
Expected result | number of input characters
1.1.1.1 4
....
1.1.1.2 5
1.1.2.1
1.2.1.1
2.1.1.1
....
1.1.1.3 6
1.1.3.1
1.3.1.1
3.1.1.1
....
2.2.2.1 7
2.2.1.2
....
2.2.2.2 8
3.2.2.1
1.2.2.3
....
2.2.2.3 9
3.3.2.1
1.2.3.3
....
3.3.3.1 10
3.3.1.3
3.1.3.3
1.3.3.3
....
3.3.3.2 11
3.3.2.3
3.2.3.3
....
3.3.3.3 12
Code
String number = "19216801";
if (number.length() == 4) {
StringBuilder sb = new StringBuilder(number)
.insert(1, ".")
.insert(1, ".")
.insert(1, ".")
.insert(1, ".");
String output = sb.toString();
System.out.println(output);
}
if (number.length() == 8) {
StringBuilder sb = new StringBuilder(number)
.insert(2, ".")
.insert(2, ".")
.insert(2, ".")
.insert(2, ".");
String output = sb.toString();
System.out.println(output);
}
if (number.length() == 12) {
StringBuilder sb = new StringBuilder(number)
.insert(3, ".")
.insert(3, ".")
.insert(3, ".")
.insert(3, ".");
String output = sb.toString();
System.out.println(output);
}
Rephrase task in next way.
imagine that ip part can have zero digit so ... is valid
then we have number.length() - 3 elements and need to put 3 dot in any position
let a, b, c be length of part
first part can be any length for(int a = 0; a < l; a++)
second one must be shorter for(int b = 0; b < l-a; b++)
same with third, total length must be l. so l>=a+b+c is constraint. c
put points in it places.
first poin just after first part (don't forget tat at first step we cut one digit from each part).
second is after first part, first dot and second part ((a +1) + 1 + (b+1))
third one the same. skip first part (a+1), dot (+1), second part (+b+1), second dot (+1) and third part (c+1) = a+b+c+5
String number = "19216801";
int l = number.length() - 3;
for(int a = 0; a < l; a++) {
for(int b = 0; b < l-a; b++){
for(int c = 0; c <l-a-b; c++){
StringBuilder sb = new StringBuilder(number);
sb.insert(a+1, ".");
sb.insert(a+b+3, ".");
sb.insert(a+b+c+5, ".");
System.out.println(sb);
}
}
}
It pretty difficult to explain, most of code come from background of my mind i just write it.
Without further information you have to rely on conjecture to form an IP address from a variable length string.
You should disallow that and ensure that your string is 12 characters long.
Once you've formed a candidate IP address though, you can validate it using the following regular expression (using String.matches)
\b(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.
(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.
(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.
(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\b
public class IPAddress {
static Queue<List<StringBuilder>> queue=new LinkedList<List<StringBuilder>>();
static int count =0;
public static void main(String[] args) {
// TODO Auto-generated method stub
try(Scanner reader=new Scanner(System.in)){
String str=reader.nextLine();
if(init(str)==-1)
System.out.println("IPAddress cannot be formed");
ipAddress();
}
}
private static void ipAddress() {
// TODO Auto-generated method stub
int noOfGroups=4;
int group=noOfGroups-1;
int countInOneLevel=1, childCount=0;
while(!queue.isEmpty() && countInOneLevel>0 && group>0){
List<StringBuilder> list=queue.poll();
countInOneLevel--;
StringBuilder currentGroup=list.get(group);
StringBuilder prevGroup=list.get(group-1);
while(currentGroup.length()>1){
prevGroup.append(currentGroup.charAt(0));
currentGroup=currentGroup.deleteCharAt(0);
if(makeIPAdress(list, group)==1 ){
childCount++;
}
}
if(countInOneLevel==0){//current level complete
countInOneLevel=childCount;
group--;
childCount=0;
}
}
System.out.println("No. of possible IPAddress: "+count);
}
private static int init(String str) {
// TODO Auto-generated method stub
int length=str.length();
if(length<4 || length>12)
return -1;
StringBuilder strgroup[]= new StringBuilder[4];
int groups=4;
for(int i=0;i<groups-1;i++){
strgroup[i]=new StringBuilder(str.substring(i,i+1));
}
strgroup[groups-1]=new StringBuilder(str.substring(3,length));
List<StringBuilder> list=new ArrayList<StringBuilder>();
for(int i=0;i<groups;i++){
list.add(strgroup[i]);
}
return makeIPAdress(list,groups-1);
}
private static int makeIPAdress(List<StringBuilder> list, int i) {
// TODO Auto-generated method stub
if(isValidIPAdress(list)){
List<StringBuilder> list1=new ArrayList<StringBuilder>();
for(int k=0;k<4;k++){
StringBuilder s=new StringBuilder(list.get(k).toString());
list1.add(s);
}
queue.offer(list1);
display(list);
count++;
return 1;
}
for(int group=i;group>0;group--){
StringBuilder currentGroup=list.get(group);
StringBuilder prevGroup=list.get(group-1);
int num=Integer.parseInt(currentGroup.toString());
while(num<0|| num>255){
prevGroup.append(currentGroup.charAt(0));
currentGroup=currentGroup.deleteCharAt(0);
num=Integer.parseInt(currentGroup.toString());
}
}
StringBuilder firstGroup=list.get(0);
int num=Integer.parseInt(firstGroup.toString());
if(num>=0 && num<=255){
List<StringBuilder> list1=new ArrayList<StringBuilder>();
for(int k=0;k<4;k++){
StringBuilder s=new StringBuilder(list.get(k).toString());
list1.add(s);
}
queue.offer(list1);
display(list);
count++;
return 1;
}
return -1;
}
private static boolean isValidIPAdress(List<StringBuilder> list) {
// TODO Auto-generated method stub
for(int group=0;group<4;group++){
int num=Integer.parseInt(list.get(group).toString());
if(num<0 || num>255)
return false;
}
return true;
}
private static void display(List<StringBuilder> list) {
// TODO Auto-generated method stub
Iterator<StringBuilder> i=list.iterator();
while(i.hasNext()){
StringBuilder s=i.next();
if(!i.hasNext())
System.out.print(s);
else
System.out.print(s+".");
}
System.out.println();
}
}
Sample Input:
2252555
Sample Output:
2.25.25.55
2.25.255.5
2.252.55.5
225.25.5.5
22.52.55.5
225.2.55.5
No. of possible IPAddress: 6
Here is a recursive solution:
public static void main(String[] args){
System.out.println(findIPs("1234567", 3));
}
public static List<String> findIPs(String s,int dots){
List<String> ips = new ArrayList<>();
for(int i =1 ;i<=3 && i < s.length(); i++){
String cip = s.substring(0,i);
if(Integer.parseInt(cip) < 256){
if(dots == 1){
if( Integer.parseInt(s.substring(i)) < 256) {
ips.add(cip + "." + s.substring(i));
}
}else {
for (String ip : findIPs(s.substring(i), dots - 1)) {
ips.add(cip + "." + ip);
}
}
}
}
return ips;
}
Here is the solution to resolve the wrong ips issue of one of the above solutions
private static List<String> ips = new ArrayList<>();
public static void main(String[] args) {
Date d = new Date();
System.out.println(posIps("19216801"));
System.out.println(new Date().getTime() - d.getTime());
}
private static List<String> posIps(String number) {
int l = number.length() - 3;
for (int a = 0; a < 3 && a < l; a++) {
for (int b = 0; b < 3 && b < l - a; b++) {
for (int c = 0; c < 3 && c < l - a - b; c++) {
StringBuilder sb = new StringBuilder(number);
if (Integer.parseInt(sb.substring(0, a + 1 )) < 256
&& Integer.parseInt(sb.substring(a + 1, a + b + 2)) < 256
&& Integer.parseInt(sb.substring(a + b + 2, a + b + c + 3)) < 256
&& Integer.parseInt(sb.substring(a + b + c + 3)) < 256) {
sb.insert(a + 1, ".");
sb.insert(a + b + 3, ".");
sb.insert(a + b + c + 5, ".");
ips.add(sb.toString());
}
}
}
}
return ips;
}
This code works fine, check it.
public static void main(String[] args) {
String input = "121212111";
for (String ipAddress : generatePossibleIpAddresses(input, 3)) {
System.out.println(ipAddress);
}
}
public static ArrayList<String> generatePossibleIpAddresses(String ipAddress, int dot) {
ArrayList<String> list = new ArrayList<String>();
if (ipAddress == null || ipAddress.length() == 0) {
return list;
}
if (dot == 0) {
int i = Integer.parseInt(ipAddress);
if (i < 256) {
list.add(ipAddress);
}
return list;
}
for (int i = 1; i <= 3; i++) {
int num = Integer.parseInt(ipAddress.substring(0, i));
if (num < 256) {
for (String str : generatePossibleIpAddresses(ipAddress.substring(i), dot - 1)) {
list.add(num + "." + str);
}
}
}
return list;
}
private static String getValidIp(List<Integer> combination, String ip) {
int from = 0;
int to = 0;
String finalIp = "";
for (int digit : combination) {
to += digit;
String ipPart = ip.substring(from, to);
if (!isValidIp(ipPart)) {
return null;
}
finalIp += ipPart + ".";
from = to;
}
return finalIp.replaceAll(".$", "");
}
public static List<List<Integer>> getOptions(String ip) {
List<Integer> baseOption = Arrays.asList(1, 2, 3);
List<List<Integer>> options = new ArrayList<>();
baseOption.forEach(i -> {
baseOption.forEach(i2 -> {
baseOption.forEach(i3 -> {
baseOption.forEach(i4 -> {
if (isRelevantOption(ip, i + i2 + i3 + i4)) {
options.add(Arrays.asList(i, i2, i3, i4));
}
});
});
});
});
return options;
}
private static boolean isRelevantOption(String ip, int sum) {
return ip.length() == sum;
}
private static boolean isValidIp(String ip) {
return Integer.parseInt(ip) < 256;
}
public static List<String> GetAllValidIpAddress(String ip) {
if (ip.length() > 12) {
System.out.println("IP is not valid");
}
List<List<Integer>> options = getOptions(ip);
return options.stream().map(c -> getValidIp(c, ip)).filter(Objects::nonNull).collect(Collectors.toList());
}
public static void main(String args[]) {
GetAllValidIpAddress("2562547").forEach(ip -> System.out.println(ip));
}

Sort String s2 using the order of String s1 using either of comparable or comparator interface

i have two strings s1 and s2 and i would like to sort s2 based on the order of appearance of letters in s1 and if other alphabets are left in s2 sort them alphabetically.
Assume i have the following;
String s1 = "war";
String s2 = "Its awesome being a programmer";
output: waaarrrIbeeeeggimmmnoopsst.
I have written a code to do that already though buut i was wondering if its possible using the comparator/comparable interface to solve it.
Listed below is my code snippet.
public class Sort {
private static String a = "war";
private static String b = "Its awesome being a programmer";
static List<Character> list = new ArrayList<>();
static public void main(String[] args) {
Character s;
Character x;
System.out.println("String to be sorted: '" + b + "'");
System.out.println("Key for sort: '" + a + "'");
/*
* put all the string in a list
*/
for (int i = 0; i < b.length(); i++) {
s = b.charAt(i);
if (s != ' ') {
list.add(s);
}
}
/*
* compare individual chac in key with individaul char in string to sort
*/
StringBuilder sb = new StringBuilder();
for (int j = 0; j < a.length(); j++) {
x = a.charAt(j);
for (int k = 0; k < b.length(); k++) {
s = b.charAt(k);
if (x == s) {
sb.append(s);
list.remove(x);
}
}
}
/*
* check if list is empty if not, sort and append the rest to the stringbuilder
*/
if (!list.isEmpty()) {
Collections.sort(list);
for (char c : list) {
sb.append(c);
}
}
System.out.println("Sorted version of string: '" + sb.toString() + "'");
}
}
private static String a = "war";
private static String b = "Its awesome being a programmer".replace(" ","");
private static String answer = "waaarrrIbeeeeggimmmnoopsst";
public static void main(String[] args) {
List<String> characters = new ArrayList<String>(b.length());
for (int i=0;i<b.length();i++){
characters.add(String.valueOf(b.charAt(i)));
}
Collections.sort(characters,new CompareIt(a));
String sortedString = listToString(characters);
System.out.println(sortedString);
System.out.println(answer);
System.out.println(answer.equals(sortedString));
}
private static String listToString(List<String> listOfStrings){
StringBuilder builder = new StringBuilder();
for (String str : listOfStrings){
builder.append(str);
}
return builder.toString();
}
private static class CompareIt implements Comparator<String>{
private final String source;
public CompareIt(String source) {
super();
this.source = source;
}
public int compare(String o1, String o2) {
int i1 = source.indexOf(o1);
int i2 = source.indexOf(o2);
if (i1==-1 && i2!=-1){
return 1;
} else if (i1!=-1 && i2==-1){
return -1;
} else if (i1!=-1 && i2!=-1){
return i1 > i2 ? 1:-1;
} else {
return o1.compareTo(o2);
}
}
}
This seems to work.
EDITED: To include sysout that result matches expected answer provided in question.
EDIT2: Typo with final indexed comparison I had ? 1:0 instead of 1:-1.
public static void main(String[] args) {
String s1 = "war";
String s2 = "Its awesome being a programmer";
String result = "";
for (int i = 0; i < s1.length(); i++) {
int len = s2.length()
- s2.replace(String.valueOf(s1.charAt(i)), "").length();
s2 = s2.replace(String.valueOf(s1.charAt(i)), "").replace(" ", "");
for (int j = 0; j < len; j++)
result = result + String.valueOf(s1.charAt(i));
}
char[] remaining = s2.toCharArray();
Arrays.sort(remaining);
for (Character c : remaining)
result = result + String.valueOf(c);
System.out.println(result);
}
Try this: I tried without using any interface.
Output:
waaarrrIbeeeeggimmmnoopsst
public static Comparator<Character> compareOn(final String key) {
return new Comparator<Character>() {
public int compare(Character c1, Character c2) {
final int indexInKey1 = key.indexOf(c1);
final int indexInKey2 = key.indexOf(c2);
final int result;
if (indexInKey1 == -1 && indexInKey2 == -1) {
result = c1.compareTo(c2); //fall back to natural ordering
} else {
if (indexInKey1 == -1) {
result = 1;
} else if (indexInKey2 == -1) {
result = -1;
} else {
result = indexInKey1 - indexInKey2;
}
}
return result;
}
};
}
public static void main(String[] args) {
final String a = "war";
final String b = "Its awesome being a programmer";
final List<Character> chars = new ArrayList<Character>();
for (char c: b.toCharArray()) {
if (c != ' ') {
chars.add(c);
}
}
Collections.sort(chars, compareOn(a));
System.out.println(chars);
}

Incrementing the number in a specified sequence

I need a sequence of a Numbers to be generated through incrementing. For Ex if it starts with 001 goes till 999 next no should be A01 again goes till A99 next should be B01. Can anybody help me to write a logic for this. Should be implemented using Java code.
simple and incompleted,
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class GenerateProgresId {
private static String[] aChar = {"A", "B", "C", "D", "E", "F", "G", "H", "I", "J",
"K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z"};
private static List<String> listA;
public GenerateProgresId() {
List<Number> list3 = new ArrayList<Number>();
List<Integer> list4 = new ArrayList<Integer>();
List<? extends Number> list5 = new ArrayList<Integer>();
List<? extends Number> list6 = list4;
list3.add(Integer.valueOf(333));
list4.add(Integer.valueOf(444));
//list5.add(Integer.valueOf(555)); // compile error
//list6.add(Integer.valueOf(666)); // compile error
Number n3 = list3.get(0);
Integer i4 = list4.get(0);
Number n5 = !list5.isEmpty() ? list5.get(0) : null;
Number n6 = list6.get(0);
System.out.printf("%s, %s, %s, %s%n", n3, i4, n5, n6);
int pomocInt = 1;
String pomocStr = "";
if (pomocInt < 10) {
pomocStr = "0" + pomocInt;
} else if (pomocInt < 100) {
pomocStr = String.valueOf(pomocInt);
} else {
pomocStr = String.valueOf(pomocInt);
}
System.out.println(pomocStr);
pomocInt = 12;
pomocStr = "";
if (pomocInt < 10) {
pomocStr = "0" + pomocInt;
} else if (pomocInt < 100) {
pomocStr = String.valueOf(pomocInt);
} else {
pomocStr = String.valueOf(pomocInt);
}
System.out.println(pomocStr);
pomocInt = 157;
pomocStr = "";
if (pomocInt < 10) {
pomocStr = "0" + pomocInt;
} else if (pomocInt < 100) {
pomocStr = String.valueOf(pomocInt);
} else if (pomocInt > 99) {
pomocStr = String.valueOf(pomocInt);
pomocStr = pomocStr.substring(pomocStr.length() - 2, pomocStr.length());
}
System.out.println(pomocStr);
listA = new ArrayList<String>();
listA.addAll(Arrays.asList(aChar));
System.out.println("From List");
System.out.println(GenerateProgresIdList(null));
System.out.println(GenerateProgresIdList(""));
System.out.println(GenerateProgresIdList("B"));
System.out.println(GenerateProgresIdList("AA"));
System.out.println(GenerateProgresIdList("AZ"));
System.out.println(GenerateProgresIdList("ZY"));
System.out.println(GenerateProgresIdList("ZZ"));
System.out.println("From String[]");
System.out.println(GenerateProgresIdString(null));
System.out.println(GenerateProgresIdString(""));
System.out.println(GenerateProgresIdString("B"));
System.out.println(GenerateProgresIdString("AA"));
System.out.println(GenerateProgresIdString("AZ"));
System.out.println(GenerateProgresIdString("ZY"));
System.out.println(GenerateProgresIdString("ZZ"));
}
public static String GenerateProgresIdList(String str) {
int lastChar = aChar.length - 1;
String retStr = "AA";
if (str != null) {
if (str.length() > 0) {
if (str.length() == 1) {
retStr = str + aChar[0];
} else if (str.length() == 2) {
int stChar = listA.indexOf(str.substring(0, 1));
int ndChar = listA.indexOf(str.substring(1, str.length()));
if ((stChar != lastChar) || (ndChar != lastChar)) {
if (ndChar == lastChar) {
retStr = listA.get(stChar + 1) + listA.get(0);
} else {
retStr = listA.get(stChar) + listA.get(ndChar + 1);
}
}
}
}
}
return retStr;
}
public static String GenerateProgresIdString(String str) {
String lastChar = aChar[aChar.length - 1];
String retStr = "AA";
if (str != null) {
if (str.length() > 0) {
if (str.length() == 1) {
retStr = str + aChar[0];
} else if (str.length() == 2) {
if ((!str.substring(0, 1).equals(lastChar)) || (!str.substring(1, str.length()).equals(lastChar))) {
String pos1 = str.substring(0, 1);
String pos2 = str.substring(1, str.length());
if ((pos2).equals(lastChar)) {
int heplInt = 0;
for (int i = 0; i < aChar.length; i++) {
if (aChar[i].equals(pos1)) {
heplInt = i + 1;
break;
}
}
retStr = aChar[heplInt] + aChar[0];
} else {
int heplInt = 0;
for (int i = 0; i < aChar.length; i++) {
if (aChar[i].equals(pos2)) {
heplInt = i + 1;
break;
}
}
retStr = pos1 + aChar[heplInt];
}
}
}
}
}
return retStr;
}
public static void main(String[] args) {
GenerateProgresId gpi = new GenerateProgresId();
}
}
Try this,
class Foo
{
private static int incr=0;
public static String getNo()
{
incr++;
if(incr%100==0)
incr++;
String no=String.valueOf(incr%100);
String str= String.valueOf((char)('A'+incr/100)) + new String(new byte[]{'0','0'},0,2-no.length()) +
String.valueOf(incr%100);
return str;
}
}
public class Test
{
public static void main(String args[]){
for(int i=1;i<=310;i++){
System.out.println(Foo.getNo());
}
}
}
Here's my (clumsy, yet hopefully correct) attempt:
class Program {
public static void main(String[] args) {
Incrementer inc = new Incrementer();
while (inc.hasNext()) {
System.out.println(inc.getNext());
}
}
}
class Incrementer {
private final static char[] prefixes = { '0', '1', '2', '3', '4', '5', '6',
'7', '8', '9', 'A', 'B', 'C' };
//all the way to 'Z' if you want, but I'm lazy
private int currentPrefix = 0;
private int currentNumber = 0;
public boolean hasNext() {
if ((currentPrefix == (prefixes.length - 1)) && currentNumber > 99) {
return false;
}
return true;
}
// this may throw ArrayIndexOutOfBoundsException, check hasNext() first
public String getNext() {
String result;
if (currentNumber > 99) {
currentNumber = 1;
currentPrefix++;
}
result = "" + prefixes[currentPrefix];
if (currentNumber <= 9) {
result += "0";
}
result += currentNumber;
currentNumber++;
return result;
}
}
One way to do this would be to make the first character, and the second 2 characters separately.
public SequenceGenerator {
private int lowerTwoDigits;
private char thirdDigit;
public SequenceGenerator () {
lowerTwoDigits = 0;
thirdDigit = '0';
}
public String nextElement() {
lowerTwoDigits++;
if (lowerTwoDigits == 100) {
lowerTwoDigits = 1;
thirdDigit++;
if (thirdDigit == '9' + 1)
thirdDigit = 'A';
}
String result = thirdDigit +
('0' + lowerTwoDigits / 10 ) +
('0' + lowerTwoDigits % 10 );
return result;
}
}
public class Main {
public static void main(String[] args) {
SequenceGenerator s = new SequenceGenerator();
int MAX = 99 * 36;
while (MAX >= 0) {
System.out.println(s.nextElement());
MAX--;
}
}
}
This should do what you are asking for, and I think you can understand what is going on in the nextElement method.
Allocate a batch of 100 numbers in one go and use them and allocate a new batch if the existing batch is exhausted. so something like String getBatchPrefix() which generates 0, "A", "B"... then create an object
class BatchIncrementer {
private final String prefix;
private final AtomicInteger incrementer;
BatchIncrementer(String pPrefix) {
incrementer = new AtomicInteger();
prefix = pPrefix;
}
Integer getNext() {
return incementer.getAndIncrement();
}
Boolean hasNext() {
return incrementer.get() < 100;
}
}
Here is a simple Alphabetic incrementor, im sure you can figure out the rest :-)
public static String incrementAlphabetic(String value, int position) {
value = value.toUpperCase();
char c = value.charAt(position);
c++;
boolean next = false;
if (c > 'Z') {
next = true;
c = 'A';
}
String n = value.substring(0, position)
+ String.valueOf(c)
+ value.substring(position + 1, value.length());
return (next && position > 0) ? incrementAlphabetic(n, position - 1) : n;
}
public static void main(String[] args) {
String start = "A";
for (int i = 0; i < 1000; i++) {
System.out.println(start = incrementAlphabetic(start, 0));
}
}
are you looking for something like this.. (not tested)
char ch='a';
int iterations=999;
int count=0;
for(int i=0;i<iterations;i++){
if(i%100==0){
ch++;
count=0;
}
System.out.println(ch+""+count);
count++;
}

Categories