I need to do a method to check two string for example bod and bot or crab and rab. The method needs to print out what the user must do in order to make them equal. For example in bod and bot it will print "replace,2,d in the string". I used this code which seems to work.
if(a.length()==b.length()){
int i;
for(i=0; i<=a.length(); i++){
if(a.charAt(i)!=b.charAt(i)){
return "replace,"+ i + "," + b.charAt(i);
}
}
}
But I am having troubles if the two string are not equal in size. I use this but it doesn't work because one of the strings is bigger.
int aS = a.length();
int bS = b.length();
if(bS - aS == 1){
int i;
for(i=0; i<=b.length(); i++){
if(b.charAt(i)!=a.charAt(i)){
return "remove," + i;
}
}
}
Can you guys give me a suggestion what method I can use to check which is the extra letter or vice versa a letter I can add and then return a string saying either to remove a character or add an extra one. Thank you
Maybe something like this?
public ArrayList<String> createConversionList(String primary, String secondary){
//Determine which string is shorter.
String shorter;
String longer;
boolean primaryIsShorter = false;
if (primary.length() >= secondary.length()){
longer = primary;
shorter = secondary;
} else{
longer = secondary;
shorter = primary;
primaryIsShorter = true;
}
//Fills an array with all the character positions that differ between the
//two strings, using the shorter string as the base.
int[] posOfCharsToChange = new int[shorter.length()];
for(int i = 0; i < shorter.length(); i++){
if(shorter.charAt(i) != longer.charAt(i)){
posOfCharsToChange[i] = i;
} else{
posOfCharsToChange[i] = -1;
}
}
//Adds to an ArrayList all of the "Replace" strings.
ArrayList<String> conversionList = new ArrayList();
for(int pos: posOfCharsToChange){
if(pos != -1){
String s = "Replace " + secondary.charAt(pos) + " with " + primary.charAt(pos) + ". \n";
conversionList.add(s);
}
}
//Depending on which string was bigger, either adds "Add" or "Remove"
//strings to the ArrayList. If the strings were the same size, does
//nothing.
if(primary.length() != secondary.length()){
if(primaryIsShorter){
for(int i = primary.length(); i < secondary.length(); i++){
String s = "Remove " + secondary.charAt(i) + ". \n";
conversionList.add(s);
}
}
else{
for(int i = secondary.length(); i < primary.length(); i++){
String s = "Add " + primary.charAt(i) + ". \n";
conversionList.add(s);
}
}
}
return conversionList;
}
My Approach works as follows
1) We take the smaller string and put all its contents in an arraylist
2) We take the bigger string and put its contents in the arraylist only if its not present in the arraylist
3) The last character in the arraylist must be removed from the bigger string to make them equal
Ex 1:
a = rab
b = crab
1) arraylist = rab -> contents of a added
2) arraylist = rabc -> only unique content of b is added
Ex 2:
a = crab
b = rab
1) arraylist = rab
2) arraylist = rabc
similarly if the positions are in the middle or not at start ,
ex : a = racb
b = rab
1) arraylist = rab
2) arraylist = rabc
public class Replace {
public static void main(String args[]) {
int p = 0, j = 0;
String a = "rab";
String b = "crab";
if (b.length() < a.length()) {
ArrayList al = new ArrayList();
for (j = 0; j < b.length(); j++) {
if (!al.contains(b.charAt(j))) {
al.add(b.charAt(j));
}
}
for (j = 0; j < a.length(); j++) {
if (!al.contains(a.charAt(j))) {
al.add(a.charAt(j));
}
}
System.out.println("Remove " + al.get(al.size() - 1)
+ " from String a");
} else {
ArrayList al = new ArrayList();
for (j = 0; j < a.length(); j++) {
if (!al.contains(a.charAt(j))) {
al.add(a.charAt(j));
}
}
for (j = 0; j < b.length(); j++) {
if (!al.contains(b.charAt(j))) {
al.add(b.charAt(j));
}
}
System.out.println("Remove " + al.get(al.size() - 1)
+ " from String b");
}
}
}
Note - The program only works under your given contraints that strings only differ in one character and the ordering of both the strings is not different if we remove or add that charcter.
Related
public static void main(String[] args)
{
loadDependencies ld = new loadDependencies();
List<String> ls = ld.loadDependenciesFromPom();
getAvailableHigherVersions ah = new getAvailableHigherVersions();
List<List<String>> vl = ah.versionListOnly();
String previousVersion=null;
for ( int a=0; a<vl.size();a++) {
List<String> tmp = vl.get(a);
for(int i=0; i<ls.size();i++){
String firstE = ls.get(i);
for(int j=0;j<tmp.size();j++) {
if (i==0 && j==0){
//xu.versionUpdate(previousVersion, tmp.get(j));
//String previousVersiontt = ls.get(i);
System.out.println(firstE + "----" + tmp.get(j));
}
/*xu.versionUpdate(previousVersion, tmp.get(j));
previousVersion=tmp.get(j);*/
//System.out.println(previousVersion+"-"+tmp.get(j));
// previousVersion = tmp.get(j);
}
}
}
}
"ls" is a String list. It contains like this
[1,4,5,7]
"vl"is a List of string list. It contains like this
[[1.5,1.6,1.7],[4.1,4.2,4.3],[5.1,5.2],[7.1,7.4]]
what I need to do is first take the 1st element of ls list
1
then i need to get the first element in the vl list
[1.5,1.6,1.7]
then output should be
[1,1.5]
then the next output would be
[1.5,1.6]
likewise iterate through the array.
Then next take the 2nd element of ls
4
then it should go like 4,4.1 then 4.1,4.2 likewise until the ls is empty.
I tried above code but some times it iterate multiple times. Any hint to fix this issue?
So if I understood well, you want something like this:
for (int a = 0; a < ls.size(); a++)
{
// Get first element
String firstE = ls.get(a);
// Get corresponding vl elements
List<String> vls = vl.get(a);
// Now print the elements
// The first element of vl should be preceeded by the corresponding element in ls
// The others by the predecessor in the same array
for (int b = 0; b < vls.size(); b++)
{
System.out.print("[");
if (b == 0)
System.out.print(firstE);
else
System.out.print(vls.get(b - 1));
System.out.println(", " + vls.get(b) + "]");
}
}
for(int i=0;i<ls.size();i++){
List<String> tmp = vl.get(i);
System.out.println(ls.get(i)+" "+temp.get(0));
for(int j=1;j<tem.size()-1;j++){
System.out.println(temp.get(j)+" "+temp.get(j+1));
}
}
for ( int a=0; a<vl.size();a++) {
List<String> tmp = vl.get(a);
String firstE = ls.get(a);
for (int j = 0; j < tmp.size(); j++) {
if (j == 0) {
//xu.versionUpdate(previousVersion, tmp.get(j));
//String previousVersiontt = ls.get(i);
System.out.println(firstE + "----" + tmp.get(j));
}
/*xu.versionUpdate(previousVersion, tmp.get(j));
previousVersion=tmp.get(j);*/
//System.out.println(previousVersion+"-"+tmp.get(j));
// previousVersion = tmp.get(j);
}
}
}
So I have to create an array of 5 chocolates, but I have to order them based on their quantities. I am not allowed to use the sort function.
import java.util.Scanner;
import java.util.Random;
public class Chocolate {
private String name;
private int quantity;
public Chocolate(String cName, int cQuantity) {
this.name = cName;
this.quantity = cQuantity;
}
public String getName() {
return name;
}
public int getQuantity() {
return quantity;
}
public int compareTo(Chocolate obj1){
if(this.quantity < obj1.quantity)
return -1;
else if (this.quantity > obj1.quantity)
return 1;
else
return 0;
}
public static void main(String args[]) {
Chocolate[] ch = new Chocolate[5];
Random rand = new Random();
Scanner scan = new Scanner(System.in);
String name;
int result;
int quantity;
for (int i = 0; i < ch.length; i++) {
System.out.println("Enter name of chocolates");
name = scan.nextLine();
quantity = rand.nextInt((19 - 1) + 1) + 1;
ch[i] = new Chocolate(name, quantity);
}
for (int i = 0; i < ch.length; i++) {
result = ch[i].compareTo(ch[i]);
System.out.println(ch[i].getName() + " " + ch[i].getQuantity());
System.out.println(result);
}
}
}
So basically I need to have a loop that uses the compareTo and orders the chocolates by quantity and then print them sorted. Cannot use .sort. Thanks
You cannot sort an array with only one loop. If you are not allowed to used sort method you can do it with a classic bubble sort:
for (int i = 0; i < ch.length; i++) {
for (int j = 0; j < ch.length - 1; j++) {
if (ch[j].compareTo(ch[j + 1]) < 0) {
Chocolate temp = ch[j];
ch[j] = ch[j + 1];
ch[j + 1] = temp;
}
}
}
But you will need for in for to achieve it.
You can do sorting without using any type of common sorting technique as long as you have these constraints:
The field to be used for sorting is integer or can be converted to integer.
The range of integer value of the field is within a small predefined range.
In your case your example satisfies both constraints.
You are sorting by cQuantity field which is an integer.
The cQuantity field is within 0 to 19 range.
What you can do is:
Create an Chocolate[20][20] array. Lets call it sorted.
Iterate over ch and put each Chocolate into the above sorted array using their getQuantity field as index. In case we have more than one Chocolate with the same getQuantity add them together under the same index.
Iterate over sorted and print its value if it is not null.
Here is the code:
Chocolate[][] sorted = new Chocolate[20][20];
for (Chocolate c : ch) {
Chocolate[] bucket = sorted[ c.getQuantity() ];
if (bucket == null) {
bucket = new Chocolate[20];
bucket[0] = c;
sorted[ c.getQuantity() ] = bucket;
}else {
//if we already have entry under this index, find next index that is not occupaed and add this one
for (int i = 0; i < bucket.length; i++) {
if (bucket[i] == null) {
bucket[i] = c;
break;
}
}
}
}
for (Chocolate[] bucket : sorted) {
if ( bucket != null) {
//System.out.println("b");
for (Chocolate c : bucket) {
if (c != null) System.out.println( c.getName() + " " + c.getQuantity() );
}
}
}
//Fill Each Alphabet
System.out.println();
for(int i = 0; i<alphabet.length; i++)
System.out.print(i + " ");
System.out.println();
for(int i = 0; i <alphabet.length; i++)
{
alphabetOriginal[i] = i;
alphabet[i] = i;
char letter = (char)(alphabetOriginal[i] + 65);
if(alphabet[i] > 9)
System.out.print(letter+ " ");
else
System.out.print(letter+ " ");
}
//Switch each character!
int position, temporary;
Random rn = new Random();
for(int i = 0; i <alphabet.length; i++)
{
int j = rn.nextInt(26);
temporary = alphabet[25-i];
alphabet[25-i] = alphabet[j];
alphabet[j] = temporary;
}
//Display the Scrambled Alphabet if they Are Interested
if(validateAffirm(decision))
{
System.out.println("\n\n\tYou can see the (randomly generated) new alphabet below!\n");
for(int i = 0; i <alphabet.length; i++)
System.out.print(alphabet[i] + " ");
System.out.println();
for(int i = 0; i<alphabet.length; i++)
{
char ScrambleLetter = (char)(alphabet[i] + 65);
if(alphabet[i] > 9)
System.out.print(ScrambleLetter + " ");
else
System.out.print(ScrambleLetter + " ");
}
}
//Use a Binary Search to Determine the Length of Each
StringBuilder sb4 = new StringBuilder(initMessage.length());
int temporaryCharValue;
for(int i = 0; i<initMessage.length(); i++)
{
temporaryCharValue = (int)(initMessage.charAt(i));
temporaryCharValue-=65;
for(int j = 0; alphabet[j] != temporaryCharValue; j++)
{
if(alphabet[j] == temporaryCharValue)
{
temporaryCharValue+=65;
char tempChar = (char)(temporaryCharValue);
sb4.append(tempChar);
System.out.println(tempChar);
sb4.toString();
}
}
}
System.out.println("\n" +sb4);
Can you help find out why my String isn't compiling to determine the final encrypted message? The arrays are defined just fine, but in my nested for loop, I cannot seem to access the proper method for combining each translated character into the final String. I am not even sure if the method translates the characters properly... (This is my first year programming, I apologize for any obvious mistakes. I am a junior in high school).
You code is hard to understand, there are constants that I don't know where they came from... however, It seems to me that the loop you mention had a definition problem... I explain:
According to your algorithm, your invariant (or looping condition) is alphabet[j] != temporaryCharValue however, the inner sentence (the IF sentence) expects that alphabet[j] == temporaryCharValue, so when lphabet[j] == temporaryCharValue is TRUE, the loop returns (or stops) and the IF Sentence is never evaluated...
After hard searchig I still haven't found the proper answer for my question and there is it:
I have to write a java program that enters an array of strings and finds in it the largest sequence of equal elements. If several sequences have the same longest length, the program should print the leftmost of them. The input strings are given as a single line, separated by a space.
For example:
if the input is: "hi yes yes yes bye",
the output should be: "yes yes yes".
And there is my source code:
public static void main(String[] args) {
System.out.println("Please enter a sequence of strings separated by spaces:");
Scanner inputStringScanner = new Scanner(System.in);
String[] strings = inputStringScanner.nextLine().split(" ");
System.out.println(String.join(" ", strings));
ArrayList<ArrayList<String>> stringsSequencesCollection = new ArrayList<ArrayList<String>>();
ArrayList<String> stringsSequences = new ArrayList<String>();
stringsSequences.add(strings[0]);
for (int i = 1; i < strings.length; i++) {
if(strings[i].equals(strings[i - 1])) {
stringsSequences.add(strings[i]);
} else {
System.out.println(stringsSequences + " " + stringsSequences.size());
stringsSequencesCollection.add(stringsSequences);
stringsSequences.clear();
stringsSequences.add(strings[i]);
//ystem.out.println("\n" + stringsSequences);
}
if(i == strings.length - 1) {
stringsSequencesCollection.add(stringsSequences);
stringsSequences.clear();
System.out.println(stringsSequences + " " + stringsSequences.size());
}
}
System.out.println(stringsSequencesCollection.size());
System.out.println(stringsSequencesCollection.get(2).size());
System.out.println();
int maximalStringSequence = Integer.MIN_VALUE;
int index = 0;
ArrayList<String> currentStringSequence = new ArrayList<String>();
for (int i = 0; i < stringsSequencesCollection.size(); i++) {
currentStringSequence = stringsSequencesCollection.get(i);
System.out.println(stringsSequencesCollection.get(i).size());
if (stringsSequencesCollection.get(i).size() > maximalStringSequence) {
maximalStringSequence = stringsSequencesCollection.get(i).size();
index = i;
//System.out.println("\n" + index);
}
}
System.out.println(String.join(" ", stringsSequencesCollection.get(index)));
I think it should be work correct but there is a problem - the sub array list's count isn't correct: All the sub arrayList's size is 1 and for this reason the output is not correct. I don't understand what is the reason for this. If anybody can help me to fix the code I will be gratefull!
I think it is fairly straight forward just keep track of a max sequence length as you go through the array building sequences.
String input = "hi yes yes yes bye";
String sa[] = input.split(" ");
int maxseqlen = 1;
String last_sample = sa[0];
String longest_seq = last_sample;
int seqlen = 1;
String seq = last_sample;
for (int i = 1; i < sa.length; i++) {
String sample = sa[i];
if (sample.equals(last_sample)) {
seqlen++;
seq += " " + sample;
if (seqlen > maxseqlen) {
longest_seq = seq;
maxseqlen = seqlen;
}
} else {
seqlen = 1;
seq = sample;
}
last_sample = sample;
}
System.out.println("longest_seq = " + longest_seq);
Lots of issues.
First of all, when dealing with the last string of the list you are not actually printing it before clearing it. Should be:
if(i == strings.length - 1)
//...
System.out.println(stringsSequences + " " + stringsSequences.size());
stringsSequences.clear();
This is the error in the output.
Secondly, and most importantly, when you do stringsSequencesCollection.add you are adding an OBJECT, i.e. a reference to the collection. When after you do stringsSequences.clear(), you empty the collection you just added too (this is because it's not making a copy, but keeping a reference!). You can verify this by printing stringsSequencesCollection after the first loop finishes: it will contain 3 empty lists.
So how do we do this? First of all, we need a more appropriate data structure. We are going to use a Map that, for each string, contains the length of its longest sequence. Since we want to manage ties too, we'll also have another map that for each string stores the leftmost ending position of the longest sequence:
Map<String, Integer> lengths= new HashMap<>();
Map<String, Integer> indexes= new HashMap<>();
String[] split = input.split(" ");
lengths.put(split[0], 1);
indexes.put(split[0], 0);
int currentLength = 1;
int maxLength = 1;
for (int i = 1; i<split.length; i++) {
String s = split[i];
if (s.equals(split[i-1])) {
currentLength++;
}
else {
currentLength = 1;
}
int oldLength = lengths.getOrDefault(s, 0);
if (currentLength > oldLength) {
lengths.put(s, currentLength);
indexes.put(s, i);
}
maxLength = Math.max(maxLength, currentLength);
}
//At this point, youll have in lengths a map from string -> maxSeqLengt, and in indexes a map from string -> indexes for the leftmost ending index of the longest sequence. Now we need to reason on those!
Now we can just scan for the strings with the longest sequences:
//Find all strings with equal maximal length sequences
Set<String> longestStrings = new HashSet<>();
for (Map.Entry<String, Integer> e: lengths.entrySet()) {
if (e.value == maxLength) {
longestStrings.add(e.key);
}
}
//Of those, search the one with minimal index
int minIndex = input.length();
String bestString = null;
for (String s: longestStrings) {
int index = indexes.get(s);
if (index < minIndex) {
bestString = s;
}
}
System.out.println(bestString);
Below code results in output as you expected:
public static void main(String[] args) {
System.out.println("Please enter a sequence of strings separated by spaces:");
Scanner inputStringScanner = new Scanner(System.in);
String[] strings = inputStringScanner.nextLine().split(" ");
System.out.println(String.join(" ", strings));
List <ArrayList<String>> stringsSequencesCollection = new ArrayList<ArrayList<String>>();
List <String> stringsSequences = new ArrayList<String>();
//stringsSequences.add(strings[0]);
boolean flag = false;
for (int i = 1; i < strings.length; i++) {
if(strings[i].equals(strings[i - 1])) {
if(flag == false){
stringsSequences.add(strings[i]);
flag= true;
}
stringsSequences.add(strings[i]);
}
}
int maximalStringSequence = Integer.MIN_VALUE;
int index = 0;
List <String> currentStringSequence = new ArrayList<String>();
for (int i = 0; i < stringsSequencesCollection.size(); i++) {
currentStringSequence = stringsSequencesCollection.get(i);
System.out.println(stringsSequencesCollection.get(i).size());
if (stringsSequencesCollection.get(i).size() > maximalStringSequence) {
maximalStringSequence = stringsSequencesCollection.get(i).size();
index = i;
//System.out.println("\n" + index);
}
}
System.out.println(stringsSequences.toString());
This question already has an answer here:
Closed 10 years ago.
Possible Duplicate:
Java code with tests - infinite loop?
Here is my code that I want to get the relationship between people, however, when I run unit test, the test ran forever and couldn't get the result, and my cpu using was high.
Here is my code. Could someone see what's wrong with it?
the string relations are multiple line inputs of string with a format "A , B" +\n" +
"C , D" where A is the parent of B and C is the parent of D.
this is the default constructor for the code and is the input format of string, we don't need to check if the format is correct
public SeeRelations(String relations){
this.relations = relations;
}
//helper function to get each line of the string
private ArrayList<String> lineRelations(){
int i;
ArrayList<String> lineRelations = new ArrayList<String>();
String[] lines = relations.split("\n");
for(i = 0; i < lines.length; i++){
lineRelations.add(lines[i]);
}
return lineRelations;
}
//helper function to put each of the relationship in arraylists
private ArrayList<ArrayList<String>> allRelations(){
int i;
ArrayList<ArrayList<String>> allRelations = new ArrayList<ArrayList<String>>();
ArrayList<String> lineRelations = lineRelations();
for(i = 0; i < lineRelations.size(); i++){
ArrayList<String> eachLine = new ArrayList<String>(Arrays.asList(lineRelations.get(i).split("\\s*,\\s*")));
allRelations.add(eachLine);
}
return allRelations;
}
this is the method to check if the input name is existent
//helper function to see if the name exist for seeRelations()
private boolean hasThisName(String name){
ArrayList<ArrayList<String>> allRelations = allRelations();
int i;
int j;
for(i = 0; i < allRelations.size(); i++){
for(j = 0; j < allRelations.get(i).size(); j++){
if(name.equals(allRelations.get(i).get(j))){
return true;
}
}
}
return false;
}
this is the function to get the generation number between two people
//helper function to get Generation number of seeRelations()
private int getGenerationNum(String person, String ancestor){
ArrayList<ArrayList<String>> allRelations = allRelations();
String name;
int i;
int j;
int generationNum = 0;
for(i = 0, j = 0, name = ancestor; i < allRelations.size(); i++){
if(name.equals(allRelations.get(i).get(0)) && !person.equals(allRelations.get(i).get(1))){
generationNum++;
ancestor = allRelations.get(i).get(1);
i = 0;
j = 1;
}
else if(ancestor.equals(allRelations.get(i).get(0)) && person.equals(allRelations.get(i).get(1))){
generationNum++;
j = 1;
break;
}
}
if(j == 0){
return 0;
}
else{
return generationNum;
}
}
this is the method to get multiple of "great" for the final output
private String great(int num){
int i;
String great = "";
for(i = 0; i < num; i++){
great += "great";
}
return great;
}
this is my final method to check the relationship between two people
public String seeRelations(String person, String ancestor){
int generationNum = getGenerationNum(person, ancestor);
String great = great(generationNum - 2);
if(!(hasThisName(person) && hasThisName(ancestor))){
return null;
}
else{
if(generationNum == 0){
return null;
}
else if(generationNum == 1){
return ancestor + " is the parent of " + person;
}
else if(generationNum == 2){
return ancestor + " is the grandparent of " + person;
}
else{
return ancestor + " is the" + " " + great +"grandparent of " + person;
}
}
}
This piece of code looks suspicious to me. It is inside a loop that depends for termination on incrementing i, but conditionally resets i back to zero. What guarantees i will ever get past 1?
if(name.equals(allRelations.get(i).get(0)) && !person.equals(allRelations.get(i).get(1))){
generationNum++;
ancestor = allRelations.get(i).get(1);
i = 0;
j = 1;
}
In general, I suggest simplifying your code until it works, then adding gradually so that you only have to debug a small piece of code at a time.