java recurrsion with ArrayList not working - java

I am doing recursion for a given phone number and print all the possible string representation of the number. The problem is in loop for (int j=0;j<ops;j++) { the size of the "perm" ArrayList keep increasing in every iteration. I want to get fixed pattern and add new number e.g perm = 11 and call recursion with tperm=110,111,112.
import java.util.*;
public class phoneNum {
public static void getSt ( List<Integer>list , List<Integer> perm ) {
Integer len = list.size();
Integer len1 = perm.size();
Integer ops = 0;
if (len == len1) {
for(int k=0;k<len;k++) {
System.out.print(" " + list.get(k));
}
for(int k=0;k<len;k++) {
System.out.print(" " + perm.get(k));
}
System.out.print("====");
System.out.print(getPattrn(list,perm));
System.out.println("\n");
} else {
for (int i=0; i<len1+1; i++) {
if(list.get(i) == 7 || list.get(i) == 9) {
ops = 4;
} else {
ops = 3;
}
for (int j=0;j<ops;j++) {
List<Integer> tperm = new ArrayList<Integer>(perm);
tperm.add(i,j);
System.out.println("Size=" + tperm.size() + " ---" + perm.size());
getSt(list,tperm);
}
}
}
}

You can add tperm.remove(i) at the end of inner for loop.

Related

[Java]Find duplicate characters in a string without hashmap and set

I have written a Java program to find duplicate characters in a string without Hashmap and set.
Below is the program,
package practice;
public class Duplicate {
public static void main(String[] args) {
String src= "abcad";
char[] srcChar= src.toLowerCase().toCharArray();
int len=srcChar.length;
int j=0;
boolean flag=false;
char ch;
// System.out.println("Length of the String is "+len1);
// System.out.println("Length of the character array is "+len);
int k=0;
for(int i=0;i<len;i++)
{
// System.out.println("i-----> "+i + " and character is "+srcChar[i]);
for(j=0;j<len;j++)
{
// System.out.println("j-----> "+j + " and character is "+srcChar[j]);
if(srcChar[i]==srcChar[j])
{
k++;
}
}
if(k>1)
{
if(srcChar[i]>1)
{
System.out.println("This character "+srcChar[i]+" has repeated "+k+ " time");
}
else
{
System.out.println("There are no characters repeated in the given string");
}
}
k=0;
}
}
}
Output here is:
This character a has repeated 2 time
This character a has repeated 2 time
Here, I want the output like
This character a has repeated 2 time
i.e. not repeating the output twice. Since the character "a" is repeated twice, the output is also repeated twice.
kindly help me to get the output once instead of twice.
Thank you,
class PrintDuplicateCharacter
{
public static void main(String[] args)
{
String str = "HelloJava";
char[] ch = str.toCharArray();
int i=0,j=0;
for(i=0;i<ch.length;i++)
{
int count = 0 ;
for( j = i+1;j<ch.length;j++)
{// 4 6 , 8 , 10
if(ch[i] == ch[j] )
{
count++;
}
}
if(count != 0)
{
System.out.print(str.charAt(i) + " Occured " + count + " time");
}
}
}
}
private static void duplicateChar(String str){
char[] arr1 = str.toUpperCase().toCharArray();
int length = str.length();
int count = 1;
String s = "";
char c1 = '\u0000';
for(int i=0;i<length;i++){
count = 1;
for(int j=i+1;j<length;j++){
if(arr1[i] == arr1[j]){
count++;
c1 = arr1[i];
}
if(j == (length-1) && c1 != '\u0000' && !s.contains(String.valueOf(c1))){
s = s+" "+String.valueOf(c1)+" No of times: "+count+"\n";
}
}
}
System.out.println("\nDuplicate char are:\n"+s);
}
You can make a 2 dimensional array, 2 wide, the source strings height. In this array you store a character when it gets replaced and add one to the amount of times it has been replaced.
Something like(I don't know if these counters are correct):
replacements[j][0] = charAt(j);
replacements[j][1] += 1;
You would have to check if the character you are replacing already exists in this array and you can only print elements of the array if they aren't null.
You print this after the original loop.
All you need to fix is to start the second loop from i instead of 0.
for (int i = 0; i < len; i++) {
for (j = i; j < len; j++) {
...
}
...
}
Imports:
import java.util.ArrayList;
import java.util.List;
Code:
public static void main(String args[]) {
String input = "abcad"; // Input value
char[] chars = input.toLowerCase().toCharArray(); // Creates ArrayList
// of all characters
// in the String
List<Character> charR = new ArrayList<>(); // Creates a List used to
// saving the Characters it
// has saved
List<Integer> valR = new ArrayList<>(); // Creates a List that will
// store how many times a
// character is repeated
for (int i = 0; i < chars.length; i++) { // Loop through items in the
// ArrayList
char c = chars[i]; // Create Character value containing the value of
// the item at the "i" index of the ArrayList
if (charR.contains(c)) { // If the List contains item...
for (int i2 = 0; i2 < charR.size(); i2++) { // Loop through its
// items
if (charR.get(i2).equals(c)) { // If you find a match...
valR.set(i2, valR.get(i2) + 1); // Increase repeated
// value by 1
i2 = charR.size(); // Stop loop
} else { // Else...
i2++; // Increase index by 1
}
}
} else { // Else...
charR.add(c); // Add the Character to the List
valR.add(1); // Add the value 1 to the List (Meaning that the
// Character repeated once)
}
}
for (int i = 0; i < charR.size(); i++) { // Loop through all the items
// in the List
System.out.println("'" + charR.get(i) + "' : " + valR.get(i)); // Display
// what
// the
// character
// is
// and
// how
// many
// times
// it
// was
// repeated
}
}
Output:
'a' : 2
'b' : 1
'c' : 1
'd' : 1
char[] array=value.toCharArray();
int count=0;
char ch;
for(int i=0;i<array.length-1;i++)
{
ch=array[i];
count=1;
if(ch!='#'){
for(int j=i+1;j<array.length;j++)
{
if(ch==array[j]){
count++;
array[j]='#';
}
}
if(count>1)
{
System.out.println("char is " + ch + "count" + count);
}
}
}
You can also solve this problem with this code like :
public static void main(String[] args) {
String src = "abcad";
char[] srcChar = src.toLowerCase().toCharArray();
int len = srcChar.length;
int j = 0;
boolean flag = false;
char ch;
// System.out.println("Length of the String is "+len1);
// System.out.println("Length of the character array is "+len);
int k = 0;
for (int i = 0; i < len; i++) {
// System.out.println("i-----> "+i + " and character is "+srcChar[i]);
for (j = 0 + i; j < len; j++) {
// System.out.println("j-----> "+j + " and character is "+srcChar[j]);
if (srcChar[i] == srcChar[j]) {
k++;
}
}
if (k > 1) {
if (srcChar[i] > 1) {
System.out.println("This character " + srcChar[i] + " has repeated " + k + " time");
} else {
System.out.println("There are no characters repeated in the given string");
}
}
k = 0;
}
}
just we need to start the inner loop with j=0+i ;
for (j = 0 + i; j < len; j++)
This will you can observe above code;

Bug or Logical Error

I'm using Netbeans, and I've written a method that's not doing exactly what it should:
private ArrayList<String[]>ProductsInStock;
public void DisplayStock() {
ArrayList<String[]> Sort = new ArrayList<String[]>();
System.out.println("");
for (int i = 0; i < ProductsInStock.size(); i++) {
if (ProductsInStock.get(i)[2].equals(Products.get(ProductCodeCB.getSelectedIndex())[1])) {
boolean foundColor = false;
int size = Sort.size();//Since the size will differ dynamically
for (int k = 0; k < size; k++) {
if (Sort.get(k)[3].equals(ProductsInStock.get(i)[3])) {
foundColor = true;
if (Sort.get(k)[4].equals(ProductsInStock.get(i)[4])) {
String S[] = Sort.get(k);
S[5] = (Integer.parseInt(Sort.get(k)[5]) + Integer.parseInt(ProductsInStock.get(i)[5])) + "";
Sort.set(k, S);
break;
}
if (k == Sort.size() - 1) {
Sort.add(ProductsInStock.get(i));
}
} else if (foundColor == true) {
Sort.add(k, ProductsInStock.get(i));
break;
}
}
System.out.print(ProductsInStock.get(0)[5]+" ");
if (foundColor == false) {
Sort.add(ProductsInStock.get(i));
}
}
}
}
}
The method should NOT change the value of ProductsInStock.get(0)[5], yet it is incrementing it by 1 everytime the method is called, I've placed the "System.out.println()" to show you how the value is actually changing. Here are the results: 1 1 1 1 1 1 1 1 2
And when i added the line "S[5]=ProductsInStock.get(i)[5];", the result changed to: 1 1 1 1 1 1 1 1 1 (as it should be):
public void DisplayStock() {
ArrayList<String[]> Sort = new ArrayList<String[]>();
System.out.println("");
for (int i = 0; i < ProductsInStock.size(); i++) {
if (ProductsInStock.get(i)[2].equals(Products.get(ProductCodeCB.getSelectedIndex())[1])) {
boolean foundColor = false;
int size = Sort.size();//Since the size will differ dynamically
for (int k = 0; k < size; k++) {
if (Sort.get(k)[3].equals(ProductsInStock.get(i)[3])) {
foundColor = true;
if (Sort.get(k)[4].equals(ProductsInStock.get(i)[4])) {
String S[] = Sort.get(k);
S[5] = (Integer.parseInt(Sort.get(k)[5]) + Integer.parseInt(ProductsInStock.get(i)[5])) + "";
Sort.set(k, S);
S[5]=ProductsInStock.get(i)[5]; //<<<<HERE>>>>
break;
}
if (k == Sort.size() - 1) {
Sort.add(ProductsInStock.get(i));
}
} else if (foundColor == true) {
Sort.add(k, ProductsInStock.get(i));
break;
}
}
System.out.print(ProductsInStock.get(0)[5]+" ");
if (foundColor == false) {
Sort.add(ProductsInStock.get(i));
}
}
}
}
As you can see, there is not a single "ProductsInStock.set()" or "ProductsInStock.get()[]= " to change any value in the arraylist.
When you write this :
Sort.add(ProductsInStock.get(i));
you are adding a reference of the ProductsInStock.get(i) array to the Sort list. Any changes done in Sort.get(Sort.size()-1) will affect the original array.
Therefore code such as
String S[] = Sort.get(k);
S[5] = ...
modifies one of the arrays of ProductsInStock List.
In order to avoid that, you should create a copy of your array before adding it to the other List :
Sort.add(Arrays.copyOf(ProductsInStock.get(i),ProductsInStock.get(i).length));

Bulls and Cows game?

For those who aren't familiar, the game is a number guessing game, where a number is chosen (non repeating; e.g 1223 is NOT chosen) and the user makes a guess and obtains information whether the number AND digit is correct, number is correct but in a wrong digit, or the number is not contained. http://en.wikipedia.org/wiki/Bulls_and_cows
(e.g number chosen => 1234, guessing 3789 will give 1 cow)
Instead of the computer choosing the number and telling the properties and player guesses, I would like to do the reverse; I type in a number and the properties - the computer gives a list of possible numbers.
Anyways, my method is:
Add all numbers that do not repeat itself to the arraylist
Delete numbers that do not satisfy the conditions.
Here is how the cow cases are done :
//Case 5: property is 4 cows;
if (property.equals("040")) {
//delete if numbers don't appear EXACTLY 4 times
if (contains != 4) { numbers.remove(i); }
//removes if the digits of the number tried corresponds with the actual number (Cow!)
else if (n.charAt(0) == first.charAt(0)) { numbers.remove(i); }
else if (n.charAt(1) == second.charAt(0)) { numbers.remove(i); }
else if (n.charAt(2) == third.charAt(0)) { numbers.remove(i); }
else if (n.charAt(3) == fourth.charAt(0)) { numbers.remove(i); }
}
It has worked for cows. Upon trying to implement bulls, it seems like using this sort of approach won't be possible. How can I do a method for bulls!? Would I need to create four more arraylists and calculate for each case? Or is ArrayList not the way to go?
For example, 1234 with 1bull would mean the number to guess is 1XXX, X2XX, XX3X or XXX4 but
I can't use this approach as it will delete all number except the input.
Thanks.
You can try this algorithm for solving -
String userAnswer = // ... getUserAnswer();
if(userAnswer == null || userAnswer.equals("")
|| !userAnswer.matches("^-?\\d+$")
|| userAnswer.split("(?<=\\G.{1})").length < 4) {
// error
}
int[] secret = (int[])// ... getSecret(request);
int[] seq = {1,2,3,4};
for(int i = 0; i < userAnswer.split("(?<=\\G.{1})").length; i++) {
seq[i] = Integer.parseInt(s[i]);
}
int bullCount = 0;
int cowCount = 0;
for(int i = -1; ++i < secret.length;) {
if(secret[i] == seq[i]) {
bullCount++;
}
}
for(int i = -1; ++i < secret.length;) {
for(int j = -1; ++j < secret.length;) {
if(secret[i] == seq[j] && i != j) {
cowCount++;
}
}
}
String snswer = bullCount + "b" + cowCount + "c";
if(Arrays.equals(secret, seq))
// win!
else
// fail!
It's wrong as if the code is 1634 and the user enters 6113, the program returns 4 cows when there is in fact 3.
Try this:
private static String findNumberOfCowsAndBulls(String firstString, String secondString) {
if(firstString.equals(secondString))
return "All Bulls:" + firstString.length();
char[] fSArr = firstString.toCharArray();
char[] sSArr = secondString.toCharArray();
int countCow = 0;
int countBull = 0;
Map<String, Integer> fSMap = new HashMap<>();
Map<String, Integer> sSMap = new HashMap<>();
for (int i = 0; i < fSArr.length; i++) {
if(i < sSArr.length){
if(fSArr[i] == sSArr[i]){
countBull++;
}
else{
updateMapOfCharsCount(fSMap, fSArr[i]);
updateMapOfCharsCount(sSMap, sSArr[i]);
}
}
else{ //fSArr is bigger than sSArr
updateMapOfCharsCount(fSMap, fSArr[i]);
}
}
if(fSArr.length < sSArr.length){ //fSArr is shorter than sSArr
for(int i = fSArr.length; i < sSArr.length - fSArr.length; i++){
updateMapOfCharsCount(sSMap, sSArr[i]);
}
}
for (Map.Entry<String, Integer> entry : fSMap.entrySet()) {
String key = entry.getKey();
if(sSMap.containsKey(key)){
if(sSMap.get(key) <= fSMap.get(key))
countCow = countCow + sSMap.get(key);
else
countCow = countCow + fSMap.get(key);
}
}
return "countCow = " + countCow + " countBull = " + countBull;
}
private static void updateMapOfCharsCount(Map<String, Integer> fsMap, char c) {
String key1 = String.valueOf(c);
if (fsMap.containsKey(key1)) {
fsMap.put(key1, fsMap.get(key1) + 1);
} else
fsMap.put(key1, 1);
}

Check if array contain integer and generate integer array without duplicate elements

How would I make it so that the line that says array.equals(guess) works and how would I change the load values method into not allowing duplicate numbers?
import java.util.Arrays;
import java.util.Random;
import javax.swing.JOptionPane;
public class Assignment {
private static int[ ] loadValues(){
int[] groupOfValues = new int[5];
Random randomized = new Random();
for (int index = 0; index < 5; index++) {
groupOfValues[index] = randomized.nextInt(39) + 1;
}
return groupOfValues;
}
private static void displayOutcome(int [ ] array, int guess){
if(array.equals(guess)){
JOptionPane.showMessageDialog(null, "Congrats, your guess of " + guess + " was one of these numbers:\n"
+ Arrays.toString(array));
}
else{
JOptionPane.showMessageDialog(null, "Sorry, your guess of " + guess + " was not one of these numbers:\n"
+ Arrays.toString(array));
}
}
public static void main(String[] args) {
int guessedConvert;
String guess;
do{
guess = JOptionPane.showInputDialog("Guess a number from 1-39");
guessedConvert = Integer.parseInt(guess);
}while(guessedConvert < 1 || guessedConvert > 39);
displayOutcome(loadValues(), guessedConvert);
}
}
Searching though an array requires a loop:
boolean found = false;
for (int i = 0 ; !found && i != array.length ; i++) {
found = (array[i] == guess);
}
if (found) {
...
}
To figure out if there are duplicates in loadValues add a similar code snippet inside the outer loop:
for (int index = 0; index < 5; index++) {
boolean found = false;
int next = randomized.nextInt(39) + 1;
// Insert a loop that goes through the filled in portion
...
if (found) {
index--;
continue;
}
groupOfValues[index] = next;
}

UVa 630 kept getting wrong answer [closed]

This question is unlikely to help any future visitors; it is only relevant to a small geographic area, a specific moment in time, or an extraordinarily narrow situation that is not generally applicable to the worldwide audience of the internet. For help making this question more broadly applicable, visit the help center.
Closed 11 years ago.
I have been working on the UVa 630 problem for 2 days, http://acm.uva.es/p/v6/630.html
I have written a working code, however constantly getting the wrong answer result after the submission, my program works fine for the given input format and generate correct result, could someone please take a look at my code and find what's wrong with it please.
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Iterator;
class Main {
String[] init;
String[] sorted;
int voca = 0;
String[] test;
private String x;
private String y;
ArrayList<ArrayList> initial = new ArrayList<ArrayList>();
char[] charArray;
String input;
void initSort(String i) {
input = i;
charArray = input.toCharArray();
}
char[] get() {
return charArray;
}
void sort(int low, int high) {
int i = low;
char pivot = charArray[low];
for (int j = low + 1; j < high; j++) {
if (charArray[j] < pivot) {
if (j > i + 1) {
exchange(i + 1, j);
}
i++;
}
}
exchange(low, i);
if (i > low + 1)
sort(low, i);
if (i + 2 < high)
sort(i + 1, high);
}
void exchange(int i, int j) {
char temp = charArray[i];
charArray[i] = charArray[j];
charArray[j] = temp;
}
// ********************************************
void begin() {
// System.out.println("begin test");
int numOfdataSet;
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
try {
numOfdataSet = Integer.parseInt(in.readLine());
do {
ArrayList currentSet = new ArrayList();
int numberOfdic;
String tempStringV;
String tempStringT;
int i = 0;
try {
String emptyLine = in.readLine();
numberOfdic = Integer.parseInt(in.readLine());
;
currentSet.add(emptyLine);
currentSet.add(Integer.toString(numberOfdic));
// System.out.println("enter numberOfdic is " +
// numberOfdic);
while (i < numberOfdic) {
tempStringV = in.readLine();
currentSet.add(tempStringV);
i++;
}
// System.out.println("input test word");
tempStringT = in.readLine();
currentSet.add(tempStringT);
while (!tempStringT.equals("END")) {
tempStringT = in.readLine();
currentSet.add(tempStringT);
}
} catch (IOException e) {
e.printStackTrace();
}
initial.add(currentSet);
numOfdataSet--;
} while (numOfdataSet != 0);
} catch (IOException e) {
}
;
print();
}
// ***************************************************
void getArrays(ArrayList<String> a) {
// read the file and put the words into a temporary array
String[] temp = new String[a.size()];
for (int i = 0; i < a.size(); i++) {
temp[i] = a.get(i);
// System.out.println("temp "+i+" is "+temp[i]);
}
// extract the vocabulary counter from the temp array
int vocaCounter;
int shift;
if (!temp[0].equals("")) {
shift = 2;
vocaCounter = Integer.parseInt(temp[1]);
} else {
shift = 2;
vocaCounter = Integer.parseInt(temp[1]);
}
// System.out.println("there are "+vocaCounter);
// store the vocabulary into the array named as init
init = new String[vocaCounter];
for (int i = shift; i < vocaCounter + shift; i++) {
init[i - shift] = temp[i];
// System.out.println(i - shift + " voca is " + init[i - shift]);
}
// store the test words into the array named as test
test = new String[temp.length - vocaCounter - shift - 1];
for (int j = 0; j < temp.length - vocaCounter - shift - 1; j++) {
test[j] = temp[j + vocaCounter + shift];
// System.out.println("test "+j+" is "+test[j]);
}
sorted = init;
}
/**
* sort the two strings
*/
void arraySorter() {
x = x.toLowerCase();
initSort(x);
sort(0, x.length());
get();
// java.util.Arrays.sort(FirstArray);
y = y.toLowerCase();
initSort(y);
sort(0, y.length());
get();
}
String getEle(String in) {
initSort(in);
sort(0, in.length());
return new String(get());
}
void print() {
Iterator<ArrayList> iterator = initial.iterator();
while (iterator.hasNext()) {
getArrays((ArrayList<String>) iterator.next());
// ****************
/**
* sort the test array and store it as the testSort array
*/
String[] testSort = new String[test.length];
for (int i = 0; i < test.length; i++) {
testSort[i] = test[i];
}
for (int i = 0; i < test.length; i++) {
testSort[i] = getEle(testSort[i]);
}
// for(int i=0;i<test.length;i++)
// {
// System.out.println("test is "+test[i]+" and test sorted is "+testSort[i]);
// }
/**
* sort the vocabulary array and store the sorted array as vocaSort
*/
String[] vocaSort = new String[init.length];
for (int i = 0; i < init.length; i++) {
vocaSort[i] = init[i];
}
for (int i = 0; i < init.length; i++) {
vocaSort[i] = getEle(vocaSort[i]);
}
// start the testing process
for (int i = 0; i < test.length; i++) {
int counter = 1;
System.out.println("Anagrams for: " + test[i]);
for (int j = 0; j < sorted.length; j++) {
// anagramTester(test[i], init[j]);
boolean result = testSort[i].equals(vocaSort[j]);// //AnagramTester();
if (result == true && counter < 10) {
System.out.println(" " + counter + ") " + init[j]);
counter++;
} else if (result == true && counter < 100) {
System.out.println(" " + counter + ") " + init[j]);
counter++;
} else if (result == true && counter < 1000) {
System.out.println("" + counter + ") " + init[j]);
counter++;
}
}
if (counter == 1)
System.out.println("No anagrams for: " + test[i]);
}
System.out.println();
}
}
/**
* main function
*
* #param args
*/
public static void main(String[] args) {
Main myWork = new Main(); // create a dinamic instance
myWork.begin();
}
}
below is the input.txt file
1
4
atol
lato
rola
tara
kola
tola
END
2
24
uhgj
uhjg
ughj
ugjh
ujhg
ujgh
hujg
hugj
hgju
hguj
hjgu
hjug
guhj
gujh
ghuj
ghju
gjuh
gjhu
jugh
juhg
jhgu
jhug
jghu
jguh
jguh
END
it was a output format issue and problem solved

Categories

Resources