How to mark loop index? - java

Hi I am trying to mark a position that already been visited
This string
String s = "123+4+3233"
and multiple index.
So I will loop it gotta be inner loop
public static void main(String[] args) {
String s = "123+4+3233";
String n = "";
int count = 0;
List<String> lists = new ArrayList<>();
for(int i=0; i < s.length(); i++){
if(s.charAt(i) > 0){
for(int k = i; k < s.length(); k++){
if(s.charAt(k) == '+'){
break;
}
if(s.charAt(k) != '+'){
n += s.charAt(k);
}
}
if(!(n.isEmpty())){
lists.add(n);
n = "";
}
if(s.charAt(i) == '+'){count++; }
}
}
System.out.println(lists);
}
and this result would come out Since I don't know how to mark the place that already visited.
CANNOT USE SPLIT
[123, 23, 3, 4, 3233, 233, 33, 3]
I just want
EXPECTED RESULT
[123, 4, 3233]

you don't have to mark the place that visited, simply advance the i index:
public static void main(String[] args) {
String s = "123+4+3233";
String n = "";
int count = 0;
List<String> lists = new ArrayList<>();
for(int i=0; i < s.length(); i++){
if(s.charAt(i) > 0){
int k = i;
for(; k < s.length(); k++){
if(s.charAt(k) == '+'){
break;
}
if(s.charAt(k) != '+'){
n += s.charAt(k);
}
}
if(!(n.isEmpty())){
lists.add(n);
n = "";
}
if(s.charAt(i) == '+'){count++; }
if(k > i)i = k - 1; //advance i to the right position
}
}
System.out.println(lists);
}
output:
[123, 4, 3233]

I think you are complicating this one a bit. Here's how I would solve it:
String s = 123+4+3233;
ArrayList<String> nums = new ArrayList<>();
int lastPlus = 0; // Keeping track of the last index at which there was a "+"
for (int j = 0 j < s.length(); j++) {
if (s.charAt(j).equals("+")) {
nums.add(s.substring(lastPlus, j));
lastPlus = j + 1; //The "+1" skips over the plus for the next substring()
}
// This last 'if' statement is for adding that last bit of numbers
if (j == s.length() - 1 && !(s.charAt(j).equals("+"))) {
nums.add(lastPlus);
}
}
This should work.

I think it can be done in a shorter way:
public static void main(String... args){
String s = "123+4+3233";
List<String> lists = new ArrayList<>();
for(int i = 0; i<s.length();i++){
String temp = "";
while(i<s.length() && s.charAt(i) != '+'){
temp+= s.charAt(i);
i++;
}
lists.add(temp);
}
System.out.println(lists);
}

Related

How to sort a String and check for anagrams?

I'm supposed to write an algorithm that tests two Strings to check if they're anagrams of each other and I have to use either BubbleSort, SelectionSort or InsertionSort.
So I used SelectionSort to sort the Strings, which I converted to char arrays beforehand, but it doesn't work and I cannot find my mistake.
public static void selectionSort(char[] arr) {
for (int i = 0; i < arr.length - 1; i++) {
int least = i;
for (int j = i + 1; j < arr.length; j++) {
if (arr[j] < arr[least])
least = j;
if (least != i) {
int swap = arr[i];
arr[i] = arr[least];
arr[least] = (char) swap;
}
}
}
}
public static boolean anagramCheck(String x, String y) {
x.trim();
y.trim();
x.toLowerCase();
y.toLowerCase();
char xarr[] = x.toCharArray();
char yarr[] = y.toCharArray();
if (x.length() != y.length())
return false;
selectionSort(xarr);
System.out.println(xarr); // I used this to check if the Strings are sorted correctly
selectionSort(yarr);
System.out.println(yarr);
if (xarr == yarr) {
System.out.println("It's an anagram.");
return true;
} else {
return false;
}
}
I'm supposed to ignore capital letters and spaces, that's why I used trim() and toLowerCase(). But it neither trims the spaces nor changes capital letters to lower case letters. Additionally, when I use more than 5 letters, it doesn't sort the given Strings alphabetically. Only one of both is sorted correctly, the other one is messed up.
I am new to Java programming so I might need some help here.
Thanks in advance
Check where I did the modification:
public static void selectionSort(char[] arr) {
for (int i = 0; i < arr.length - 1; i++) {
int least = i;
for (int j = i + 1; j < arr.length; j++) {
if (arr[j] < arr[least])
least = j;
}
if (least != i) {
int swap = arr[i];
arr[i] = arr[least];
arr[least] = (char) swap;
}
}
}
In anagramCheck function:
x = x.trim(); // it returns trim string
y = y.trim();
x = x.toLowerCase(); // return lower-case string
y = y.toLowerCase();
This should work. But I used bubbleSort
class HelloWorld {
public static void main(String[] args) {
System.out.println(anagramCheck("listen", "silent"));
}
public static boolean anagramCheck(String x, String y) {
x = x.trim();
y = y.trim();
x = x.toLowerCase();
y = y.toLowerCase();
char xarr[] = x.toCharArray();
char yarr[] = y.toCharArray();
if (x.length() != y.length())
return false;
x = bubbleSort(xarr);
System.out.println(xarr); // I used this to check if the Strings are sorted correctly
y = bubbleSort(yarr);
System.out.println(yarr);
if (x.equals(y)) {
System.out.println("It's an anagram.");
return true;
} else {
return false;
}
}
public static String bubbleSort(char[] arr) {
int n = arr.length;
for (int i = 0; i < n-1; i++){
for (int j = 0; j < n-i-1; j++){
if (arr[j] > arr[j+1])
{
// swap arr[j+1] and arr[j]
char temp = arr[j];
arr[j] = arr[j+1];
arr[j+1] = temp;
}
}
}
return String.valueOf(arr);
}
}

Counting number of duplicates in a given array

Input: 1,4,2,6,7,5,1,2
Output:2
Counting the number of duplicated numbers in a given array for java. I first sorted the array and then counted duplicates. It's showing me error that variable c is not used and that this method should return value of int.
public class Duplicates
public static void main(String[] args) {
int[]list;
int[]c;
int[] c = new int[list.length];
int temp;
for (int i = 0; i < list.length - 1; i++) {
for (int j = i + 1; j < list; j++) {
if (list[I] > list[j]) {
temp = list[i];
list[i] = list[j];
list[j] = temp;
c = list;
}
}
}
int n = 0;
int counter = 0;
int a = -1;
for (int i = 0; i < c.length; ++i) {
if (c[i] == a) {
++n;
if (n == 1) {
++counter;
if (counter == 1) {
System.out.print(c[i]);
} else {
System.out.print("," + c[i]);
}
}
} else {
a = c[i];
n = 0;
}
}
System.out.println("\nNumber of Duplicated Numbers in array:" + counter);
}
}
It's showing me error that variable c is not used
This should be a warning. So the code should still run correctly even with this is showing.
this method should return value of int
This is a compilation error and since you are not returning any int array at the end of the method, your method's return type should be void. You should change your method signature as below,
public static void c(int[] list)
Otherwise you will need to return an int array at the end of your method.
After fixing your code,
public class Duplicates {
public static void main(String[] args) {
int[] list = new int[]{1, 4, 2, 6, 7, 5, 1, 2};
int temp;
for (int i = 0; i < list.length; ++i) {
for (int j = 1; j < (list.length - i); ++j) {
if (list[j - 1] > list[j]) {
temp = list[j - 1];
list[j - 1] = list[j];
list[j] = temp;
}
}
}
int n = 0, counter = 0;
int previous = -1;
for (int i = 0; i < list.length; ++i) {
if (list[i] == previous) {
++n;
if (n == 1) {
++counter;
if (counter == 1) {
System.out.print(list[i]);
} else {
System.out.print(", " + list[i]);
}
}
} else {
previous = list[i];
n = 0;
}
}
System.out.println("\nNumber of Duplicated Numbers in array: " + counter);
}
}

java, how to find the amount of letter in a string without repeats

I'm trying to build a function, that gets a string of letters, and prints the amount of each letter in the string.
for example:
input: String = "aaabbaccxyxyx"
output: 4a2b2c3x2y
This is what I've come up with:
public class Q1 {
public static String numLetters(String s){
String end = new String();
int counter = 0;
char c,d;
for(int i=0; i<s.length();i++){
c = s.charAt(i);
for(int j=0; j<s.length();j++){
d = s.charAt(j);
if(c == d){
counter++;
}
}
end = end + counter+c;
counter = 0;
}
return end;
}
but, this is the output: 4a4a4a2b2b4a2c2c3x2y3x2y3x
A lot of repeats..
Any help how to make it right?
Keep in mind, the function needs to return a string, not just prints it out.
Thanks! =)
I would make an int array to keep the count of each letter in in the string. Because there are 26 letters, the length of the array should be 26:
public static String numLetters(String s) {
int[] count = new int[26];
for (int i = 0; i < s.length(); i++) {
char c = s.charAt(i);
count[(int)(c - 'a')]++;
}
String ans = "";
for (int i = 0; i < 26; i++) {
if (count[i] != 0) {
ans += String.valueOf(count[i]) + (char)(i + 'a');
}
}
return ans;
}
A straightforward variant could look like this:
public static String countChars(String arg) {
String res = "";
boolean[] counted = new boolean[arg.length()];
for (int i = 0; i < counted.length; i++) {
if (!counted[i]) {
char c = arg.charAt(i);
int counter = 1;
for (int j = i + 1; j < counted.length; j++) {
if (arg.charAt(j) == c) {
counter++;
counted[j] = true;
}
}
res += counter + "" + c;
}
}
return res;
}
If you want to keep your original structure, I suggest using a StringBuilder so that you can delete characters that you have already seen. In case you delete a character, you have to adjust your indexes i and j.
public static String numLetters(String str){
StringBuilder s = new StringBuilder(s);
String end = new String();
int counter = 0;
char c,d;
for(int i=0; i<s.length();i++){
c = s.charAt(i);
for(int j=0; j<s.length();j++){
d = s.charAt(j);
if(c == d){
s.deleteCharAt(j);
if (i >= j) i--;
j--;
counter++;
}
}
end = end + counter+c;
counter = 0;
}
return end;
}
Try this:
int count = StringUtils.countMatches("a.b.c.d", ".");

Getting All Possibilities - Schoolwork

What I need to do is take a String array with each element having an exact length of 2, and find all possible combinations of the the elements, using each character within each String. By that I mean the String array {"Ss", "Ff"} returns "SF", "Sf", "sF", "sf". I have already tried a loop method that counts the iteration and then chooses a letter based on that, but it only works for arrays with a single element:
public String [] generatePossibilities(String [] s)
{
if(s[0].length() != 2)
throw new IllegalArgumentException();
String [] r = new String [s.length * 2];
for(int i = 0; i < r.length; i++)
{
r[i] = getPossibility(i, s);
}
return r;
}
private String getPossibility(int iteration, String [] source)
{
int [] choose = new int [source.length];
for(int i = 0; i < choose.length; i++)
{
choose[i] = 0;
}
for(int i = choose.length - 1; i >= 0; i--)
{
if(iteration < 1)
break;
choose[i] = 1;
iteration--;
}
String result = "";
for(int i = 0; i < source.length; i++)
result += source[i].substring(choose[i], choose[i] + 1);
return result;
}
Solved Thanks Sven!
public String [] generatePossibilities(String [] s)
{
if(s[0].length() != 2)
throw new IllegalArgumentException();
ArrayList<String> ra = new ArrayList<String>();
for(int i = s.length - 1; i >= 0; i--)
{
for(int j = 0; j < s[i].length(); j++)
{
String c = s[i].substring(j, j + 1);
if(ra.size() < 2)
{
ra.add(c);
}
else
{
for(int k = 0; k < ra.size(); k++)
{
String s1 = ra.get(k);
if(s1.substring(0, 1).equalsIgnoreCase(c))
continue;
else
{
s1 = c + s1;
ra.add(s1);
}
}
}
}
for(int j = 0; j < ra.size(); j++)
{
if(ra.get(j).length() != s.length - i)
{
ra.remove(j);
j--;
}
}
}
String [] r = new String [ra.size()];
for(int i = 0; i < r.length; i++)
{
r[i] = ra.get(i);
}
return r;
}
I would iterate the array of character tuples from last element to first. In each step you append to each current character the possibilities of the last iteration. You therefore double the elements in each step.
So for your example in the first iteration you have {Ff} and this would result to the two strings "F" and "f". In the next step you take each character of {Ss} and append each string of the last step to it getting "SF", "Sf", "sF" and "sf". You could then continue with further character tuples.

How to generate combinations obtained by permuting 2 positions in Java

I have this problem, I need to generate from a given permutation not all combinations, but just those obtained after permuting 2 positions and without repetition. It's called the region of the a given permutation, for example given 1234 I want to generate :
2134
3214
4231
1324
1432
1243
the size of the region of any given permutation is , n(n-1)/2 , in this case it's 6 combinations .
Now, I have this programme , he does a little too much then what I want, he generates all 24 possible combinations :
public class PossibleCombinations {
public static void main(String[] args) {
Scanner s=new Scanner(System.in);
System.out.println("Entrer a mumber");
int n=s.nextInt();
int[] currentab = new int[n];
// fill in the table 1 TO N
for (int i = 1; i <= n; i++) {
currentab[i - 1] = i;
}
int total = 0;
for (;;) {
total++;
boolean[] used = new boolean[n + 1];
Arrays.fill(used, true);
for (int i = 0; i < n; i++) {
System.out.print(currentab[i] + " ");
}
System.out.println();
used[currentab[n - 1]] = false;
int pos = -1;
for (int i = n - 2; i >= 0; i--) {
used[currentab[i]] = false;
if (currentab[i] < currentab[i + 1]) {
pos = i;
break;
}
}
if (pos == -1) {
break;
}
for (int i = currentab[pos] + 1; i <= n; i++) {
if (!used[i]) {
currentab[pos] = i;
used[i] = true;
break;
}
}
for (int i = 1; i <= n; i++) {
if (!used[i]) {
currentab[++pos] = i;
}
}
}
System.out.println(total);
}
}
the Question is how can I fix this programme to turn it into a programme that generates only the combinations wanted .
How about something simple like
public static void printSwapTwo(int n) {
int count = 0;
StringBuilder sb = new StringBuilder();
for(int i = 0; i < n - 1;i++)
for(int j = i + 1; j < n; j++) {
// gives all the pairs of i and j without repeats
sb.setLength(0);
for(int k = 1; k <= n; k++) sb.append(k);
char tmp = sb.charAt(i);
sb.setCharAt(i, sb.charAt(j));
sb.setCharAt(j, tmp);
System.out.println(sb);
count++;
}
System.out.println("total=" + count+" and should be " + n * (n - 1) / 2);
}

Categories

Resources