So I have been creating a Word-Puzzle which I recently got stuck on a index out of bounds problem. This has been resolved however the program is not doing what I would like it to do. The Idea i that the test class will print 3 words in an array e.g. [FEN, GNU, NOB] (and yes they are apparently real english words). Then check to see if the first letter of each word combined is a word and so forth e.g. FGN if so add it to the next ArrayList else start again. Ideal output would be [FEN, GNU, NOB] [FGN, ENO, NUB] for example. However the current output is [FEN, GNU, NOB] [SOY, SOY, SOY] or [FEN, GNU, NOB] [].
The Test Class
public class Test_WordPuzzleGenerator {
public static void main(String[] args) throws FileNotFoundException {
System.out.println("Test 1: size 3");
int size = 3;
Puzzle.WordPuzzleGenerator.generatePuzzle(size);
}
}
WordGenerator:
public class WordPuzzleGenerator {
static ArrayList<String> wordList = new ArrayList<String>();
public static void generatePuzzle(int size) throws FileNotFoundException {
ArrayList<String> puzzleListY = new ArrayList<String>();
ArrayList<String> puzzleListX = new ArrayList<String>();
String randomXWord;
String letterSize = "" + size;
makeLetterWordList(letterSize);
boolean finished = false;
while ( !finished ) {
finished = true;
puzzleListX.clear();
puzzleListY.clear();
for (int i = 0; i < size; i++) {
int randomYWord = randomInteger(wordList.size());
String item = wordList.get(randomYWord);
puzzleListY.add(item);
}
for (int i = 0; i < puzzleListY.size(); i++) {
StringBuilder sb = new StringBuilder();
for (int j = 0; j < puzzleListY.size(); j++) {
sb.append(puzzleListY.get(j).charAt(i));
}
randomXWord = sb.toString();
if (!wordList.contains(randomXWord)) {
break;
}
puzzleListX.add(randomXWord);
if (puzzleListX.size() == size){
finished = false;
}
}
}
System.out.print(puzzleListY);
System.out.print(puzzleListX);
}
public static int randomInteger(int size) {
Random rand = new Random();
int randomNum = rand.nextInt(size);
return randomNum;
}
public static void makeLetterWordList(String letterSize) throws FileNotFoundException {
Scanner letterScanner = new Scanner( new File (letterSize + "LetterWords.txt"));
wordList.clear();
while (letterScanner.hasNext()){
wordList.add(letterScanner.next());
}
letterScanner.close();
}
}
I think you are confusing yourself with that finished variable. Replace the while condition with puzzleListX.size() != size and your code should work.
Related
I'm trying to build an Array with 5 strings in there; indexed 0 - 4. After this I need to shuffle the different pieces in the array rounds. The problem that I'm having is that is creating 5 different arrays I think? Could someone explain to me what I'm doing wrong and how to fix it?
To give an better understanding; this is the input of the fileScanner:
5,4 4,5 8,7=6,3 3,2 9,6 4,3=7,6=9,8=5,5 7,8 6,5 6,4
class Pirate {
public static final int MAX_ELEMENTS = 5;
String [] coordinateArray;
int position;
PrintStream out;
Pirate() {
out = new PrintStream(System.out);
}
void addInOrginalArray (String coordinateRowInput) {
coordinateArray = new String [MAX_ELEMENTS];
int position = 0;
coordinateArray[position] = coordinateRowInput;
for (int i = 0; i < coordinateArray.length; i++) {
position += 1;
System.out.println(i + "\t" + coordinateArray [i]);
}
}
void start() {
Scanner fileScanner = UIAuxiliaryMethods.askUserForInput().getScanner();
fileScanner.useDelimiter("=");
while (fileScanner.hasNext()) {
String coordinateRowInput = fileScanner.next();
Scanner coordinateInputScanner = new Scanner(coordinateRowInput);
addInOrginalArray(coordinateRowInput);
}
}
public static void main(String[] argv) {
new Pirate().start();
}
}
I have tried to print all the paths which give the given amount. But my code does not work properly. I think I am missing some points to print all possible combinations. For example;
if amount: 7 and startCoin = 25, the program needs to give me:
{5,1,1} and {1,1,1,1,1,1,1}.
Can you help me to fix these problem?
Note: Preferably Java Solutions
class Solution {
static int[] coinSet = {1,5,10,25};
static List<List<Integer>> possibleWays = new ArrayList<>();
static List<Integer> currentWay = new ArrayList<>();
private static int makeChange(int amount, int startCoin){
boolean flag = false;
for(int i =0 ; i < coinSet.length ; i++){
if(coinSet[i] == startCoin) {
flag =true;
}
}
if(!flag){
throw new IllegalArgumentException("startCoin has to be in the specified range");
}
int nextCoin = 0;
switch(startCoin) {
case 25:
nextCoin = 10;
break;
case 10:
nextCoin = 5;
break;
case 5:
nextCoin = 1;
break;
case 1:
possibleWays.add(currentWay);
currentWay = new ArrayList<>();
return 1;
}
int ways = 0;
for(int count = 0; count * startCoin <= amount; count++){
ways += makeChange(amount - (count * startCoin),nextCoin);
}
return ways;
}
public int calculateNumberOfWays(int amount, int startCoin) throws Exception {
if (amount == 0) {
throw new Exception(); }
return makeChange(amount, startCoin);
}
public static void main(String[] args) {
System.out.println(makeChange(5,25));
System.out.println(possibleWays);
}
}
This can be solved using backtracking but that is not very efficient, below is the working java code
/**
* Created by sumit sharma on 3/1/2016.
*/
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Random;
public class Main {
static int[] coinSet = {1,5,10,25};
static List<List<Integer>> possibleWays = new ArrayList<>();
static List<Integer> currentWay = new ArrayList<>();
public static void main(String[] args) {
List<Integer> countOfCoins = new ArrayList<>();
makeChange(7, 0, countOfCoins);
//System.out.print(possibleWays);
}
private static int makeChange(int amount, int startCoinIdx, List<Integer> coinsSoFar) {
if(startCoinIdx == coinSet.length){
if(amount == 0){
possibleWays.add(coinsSoFar);
System.out.println(coinsSoFar);
}
//System.out.println(coinsSoFar);
return 0;
}
for(int count = 0;(count*coinSet[startCoinIdx]) <= amount;count++){
List<Integer> temp = new ArrayList<>();
for(int i = 0;i < coinsSoFar.size();i++) temp.add(coinsSoFar.get(i));
for(int i = 0;i < count;i++) temp.add(coinSet[startCoinIdx]);
makeChange(amount - (count * coinSet[startCoinIdx]),startCoinIdx+1, temp);
temp.clear();
}
return 0;
}
}
Link to solution on Ideone : http://ideone.com/kIckmG
I need to create a JAVA method: public static int[] Numb() that reads and returns a series of positive integer values. If the user enters -1 we should stop accepting values, and then I want to call it in the main method. And we should return to the user integers that he entered them, with the total number.
So if he entered the following:
5 6 1 2 3 -1
So the total number is : 6
The numbers entered are: 5 6 1 2 3 -1
I tried the following:
class Ideone
{
public static void main (String[] args) throws java.lang.Exception
{
// your code goes here
}
public static int[] readNumbers(int[] n)
{
int[] a = new int[n.length];
Scanner scan = new Scanner(System.in);
for(int i = 0;i<n.length;i++) {
String token = scan.next();
a[i] = Integer.nextString();
}
}
}
And here is a fiddle of them. I have an error that said:
Main.java:21: error: cannot find symbol
a[i] = Integer.nextString();
I am solving this exercise step by step, and I am creating the method that reads integers. Any help is appreciated.
Integer.nextString() doesn't exist, to get the next entered integer value, you may change your loop to either :
for(int i = 0;i<n.length;i++) {
a[i] = scan.nextInt();
}
or as #vikingsteve suggested :
for(int i = 0;i<n.length;i++) {
String token = scan.next();
a[i] = Integer.parseInt(token);
}
public static void main(String[] args) {
List<Integer> numList = new ArrayList<>();
initializeList(numList);
System.out.println("Num of integer in list: "+numList.size());
}
public static void initializeList(List<Integer> numList) {
Scanner sc = new Scanner(System.in);
boolean flag = true;
while(flag) {
int num = sc.nextInt();
if(num==-1) {
flag = false;
}else {
numList.add(num);
}
}
sc.close();
}
Since the number of integers is unknown, use ArrayList. It's size can be altered unlike arrays.
You can create something like arraylist on your own..it can be done like this:
public class Test {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
CustomArray c = new CustomArray(3);
boolean flag = true;
while (flag) {
int num = sc.nextInt();
if (num == -1) {
flag = false;
} else {
c.insert(num);
}
System.out.println(Arrays.toString(c.numList));
}
sc.close();
}
}
class CustomArray {
int[] numList;
int size; // size of numList[]
int numOfElements; // integers present in numList[]
public CustomArray(int size) {
// TODO Auto-generated constructor stub
numList = new int[size];
this.size = size;
numOfElements = 0;
}
void insert(int num) {
if (numOfElements < size) {
numList[numOfElements++] = num;
} else {
// list is full
size = size * 2; //double the size, you can use some other factor as well
//create a new list with new size
int[] newList = new int[size];
for (int i = 0; i < numOfElements; i++) {
//copy all the elements in new list
newList[i] = numList[i];
}
numList = newList;//make numList equal to new list
numList[numOfElements++] = num;
}
}
}
Hi guys I have been making a test class for my word puzzle game and the out put is printing the objects reference number to the object. Anyone got the solution to print the return statement of the object.
Output:
Generator stats: word-puzzles generated from words of length 3
Puzzle.WordPuzzleGenerator#c68c3Puzzle.WordPuzzleGenerator#b2002fPuzzle.WordPuzzleGenerator#2a4983Puzzle.WordPuzzleGenerator#406199Puzzle.WordPuzzleGenerator#c7b00cPuzzle.WordPuzzleGenerator#1f6f296Puzzle.WordPuzzleGenerator#1df5a8fPuzzle.WordPuzzleGenerator#b2a2d8Puzzle.WordPuzzleGenerator#1e13d52Puzzle.WordPuzzleGenerator#80fa6f
Test Class
public class Test_WordPuzzleGenerator {
public static void main(String[] args) throws FileNotFoundException {
int sizeTest1 = 3;
System.out
.println("Generator stats: word-puzzles generated from words of length "
+ sizeTest1);
for (int i = 0; i < 10; i++) {
WordPuzzleGenerator puzzle = new WordPuzzleGenerator(sizeTest1);
System.out.print(puzzle);
}
int sizeTest2 = 3;
System.out
.println("Generator stats: word-puzzles generated from words of length "
+ sizeTest2);
for (int i = 0; i < 10; i++) {
new WordPuzzleGenerator(sizeTest2);
}
}
}
Main program:
public class WordPuzzleGenerator {
static ArrayList<String> wordList = new ArrayList<String>();
public WordPuzzleGenerator(int size) throws FileNotFoundException {
ArrayList<String> puzzleListY = new ArrayList<String>();
ArrayList<String> puzzleListX = new ArrayList<String>();
String randomXWord;
String letterSize = "" + size;
makeLetterWordList(letterSize);
boolean finished = false;
while ( !finished ) {
finished = true;
puzzleListX.clear();
puzzleListY.clear();
for (int i = 0; i < size; i++) {
int randomYWord = randomInteger(wordList.size());
String item = wordList.get(randomYWord);
puzzleListY.add(item);
}
for (int i = 0; i < puzzleListY.size(); i++) {
StringBuilder sb = new StringBuilder();
for (int j = 0; j < puzzleListY.size(); j++) {
sb.append(puzzleListY.get(j).charAt(i));
}
randomXWord = sb.toString();
if (!wordList.contains(randomXWord) && !puzzleListY.contains(randomXWord)) {
finished = false;
break;
}
puzzleListX.add(randomXWord);
}
}
toString(puzzleListX, puzzleListY);
}
public static int randomInteger(int size) {
Random rand = new Random();
int randomNum = rand.nextInt(size);
return randomNum;
}
public static void makeLetterWordList(String letterSize) throws FileNotFoundException {
Scanner letterScanner = new Scanner( new File (letterSize + "LetterWords.txt"));
wordList.clear();
while (letterScanner.hasNext()){
wordList.add(letterScanner.next());
}
letterScanner.close();
}
public static String toString(ArrayList<String> ArrayList1, ArrayList<String> ArrayList2){
StringBuilder group1 = new StringBuilder();
for (int i = 0; i < ArrayList1.size(); i++) {
group1.append(ArrayList1.get(i) + " ");
}
String wordsInString1 = group1.toString();
StringBuilder group2 = new StringBuilder();
for (int i = 0; i < ArrayList2.size(); i++) {
group2.append(ArrayList2.get(i) + " ");
}
String wordsInString2 = group2.toString();
return String.format("\t( %s) ( %s)", wordsInString1, wordsInString2);
}
}
Your WordPuzzleGenerator class does not override Object's toString. Instead it contains a static toString method with a different signature.
You need a method of this signature in your WordPuzzleGenerator class :
#Override
public String toString()
{
...
}
After taking another look, it appers your WordPuzzleGenerator has only static methods and no instance members, so it's unclear what you expect toString to return, or in other words - it's not clear what System.out.print(puzzle); is expected to print.
EDIT:
If you want toString() to print the Lists created in your constructor, you should make them instance members :
ArrayList<String> puzzleListY;
ArrayList<String> puzzleListX;
public WordPuzzleGenerator(int size) throws FileNotFoundException {
puzzleListY = new ArrayList<String>();
puzzleListX = new ArrayList<String>();
...
}
Then you can override toString like this :
#Override
public String toString()
{
return WordPuzzleGenerator.toString (puzzleListX,puzzleListY);
}
you'll have to override the toString method of your objects, since your object inheris from java object
#Override
public String toString(){
\\mystring build up...
return mystring;
notice the override annotation, thats what does the trick ;)
happy coding!
try to override 'toString' method in your class as follows:
#Override
public String toString()
{
//your code
}
For example if the input is "name" and the minGram is 1 and maxGramSize is 2 output will consist of n,a,m,e,na,am,me. If the minGram=2, maxGram=4 inputWord=name, output = na,am,me,nam,ame,name.
Function signature can be something like this:
public List<String> generateNGrams(String input, int minGramSize, int maxGramSize)
Initially I tried doing it with for loops, but I was finding it hard to follow the indices. Then I tried solving it using recursion with pen and paper but I'm still struggling with it. Can someone help me with this?
One solution:
private static void addNgrams(final int size, final String input,
final List<String> list)
{
final int maxStartIndex = input.length() - size;
for (int i = 0; i < maxStartIndex; i++)
list.add(input.stubString(i, i + size));
}
public List<String> generateNGrams(final String input, final int minSize,
final int maxSize)
{
final List<String> ret = new ArrayList<>();
for (int size = minSize; size <= maxSize; size++)
addNgrams(size, input, ret);
return ret;
}
Note: lacks basic error checkings (for instance, maxSize greater than the size of input; minSize greater than maxSize; others); left as an exercise.
Here is a program that recursively generates nGrams: This code also handles the tail grams.
import java.util.ArrayList;
public class NGrams {
ArrayList<String> nGrams = new ArrayList<String>();
public void generateNGrams(String str, int n) {
if (str.length() == n ) {
int counter = 0;
while (counter < n) {
nGrams.add(str.substring(counter));
counter++;
}
return;
}
int counter = 0;
String gram = "";
while (counter < n) {
gram += str.charAt(counter);
counter++;
}
nGrams.add(gram);
generateNGrams(str.substring(1), n);
}
public void printNGrams() {
for (String str : nGrams) {
System.out.println(str);
}
}
public static void main(String[] args) {
NGrams ng = new NGrams();
ng.generateNGrams("hello world", 3);
ng.printNGrams();
}
}
Output:
hel
ell
llo
lo
o w
wo
wor
orl
rld
ld
d