I have this assignment for my university https://cs1331.gitlab.io/fall2018/hw2/hw2-source-model.html. I wrote the code but when I run the program I get this message at the console :
Exception in thread "main" java.lang.StringIndexOutOfBoundsException: begin 0, end -1, length 2
at java.base/java.lang.String.checkBoundsBeginEnd(String.java:3107)
at java.base/java.lang.String.substring(String.java:1873)
at homework1.SourceModel.main(SourceModel.java:127)
Here is my code for this assignment with comments :
package homework1;
import java.util.Scanner;
import java.io.File;
import java.io.FileNotFoundException;
public class SourceModel {
//initialize variables so they can be accessed everywhere
private String modelName;
private int[][] characterCount;
private double[] rowCount;
private double[][] probability;
/**
*
* #param name takes the name of the corpus
* #param fileName takes the filesName of corpus
*/
public SourceModel(String name, String fileName) {
modelName = name;
characterCount = new int[26][26];
rowCount = new double[26];
probability = new double[26][26];
System.out.println("Training " + name + "model...");
try {
Scanner scan = new Scanner(new File(fileName));
String temp = "";
//append all of the text
while (scan.hasNext()) {
temp += scan.next();
}
//only keeps the letters and makes them lowercase
temp = temp.replaceAll("[^A-Za-z]+", "").toLowerCase();
System.out.println(temp);
//iterates trough each letter then puts the letters
//sequence to the respective row and column
for (int i = 0; i < (temp.length() - 1); i++) {
char firstLetter = temp.charAt(i);
char secondLetter = temp.charAt(i + 1);
//index based on ASCII values
characterCount[(int) firstLetter - 97][(int) secondLetter - 97]++;
rowCount[(int) firstLetter - 97]++;
}
//calculates the probability by dividing the count
//by the total counts in each row
for (int i = 0; i < probability.length; i++) {
for (int j = 0; j < probability[i].length; j++) {
if (rowCount[i] == 0) {
rowCount[i] = 0.01;
}
probability[i][j] = (((double) characterCount[i][j]) / rowCount[i]);
if (probability[i][j] == 0) {
probability[i][j] = 0.01;
}
}
}
System.out.println("done");
}
catch (FileNotFoundException e) {
e.printStackTrace();
}
}
/**
*
* #return a string which contains the name
*/
public String getName() {
return modelName;
}
/**
* #return a string with the matrix
*/
public String toString() {
String matrix = "";
matrix += "";
for (int i = 97; i < 123; i++) {
matrix += " ";
matrix += (char) i;
}
matrix += ("\n");
for (int i = 0; i < probability.length; i++) {
matrix += ((char) (i + 97) + " ");
for (int j = 0; j < probability[i].length; j++) {
matrix += String.format("%.2f", probability[i][j]);
matrix += ("");
}
matrix += "\n";
}
return matrix;
}
/**
*
* #param test a set of letters to test
* #return the probability for the word
*/
public double probability(String test) {
test = test.replaceAll("[^A-Za-z]+", "").toLowerCase();
double stringProbability = 1.0;
for (int i = 0; i < test.length() - 1; i++) {
int firstIndex = (int) (test.charAt(i)) - 97;
int secondIndex = (int) (test.charAt(i + 1)) - 97;
stringProbability *= probability[firstIndex][secondIndex];
}
return stringProbability;
}
/**
*
* #param args the command line arguments
*/
public static void main(String[] args) {
SourceModel[] models = new SourceModel[args.length - 1];
for (int i = 0; i < args.length - 1; i++) {
models[i] = new SourceModel(args[i].substring(0, args[i].indexOf(".")), args[i]);
}
System.out.println("Analyzing: " + args[args.length - 1]);
double[] normalizedProbability = new double[args.length - 1];
double sumProbability = 0;
for (int i = 0; i < args.length - 1; i++) {
sumProbability += models[i].probability(args[args.length - 1]);
}
//normalize the probability in respect to the values given
for (int i = 0; i < normalizedProbability.length; i++) {
normalizedProbability[i] = models[i].probability(args[args.length - 1]) / sumProbability;
}
int highestIndex = 0;
for (int i = 0; i < args.length - 1; i++) {
System.out.print("Probability that test string is");
System.out.printf("%9s: ", models[i].getName());
System.out.printf("%.2f", normalizedProbability[i]);
System.out.println("");
if (normalizedProbability[i] > normalizedProbability[highestIndex]) {
highestIndex = i;
}
}
System.out.println("Test string is most likely " + models[highestIndex].getName() + ".");
}
}
Others have already pointed this out, but for this line:
models[i] = new SourceModel(args[i].substring(0, args[i].indexOf(".")), args[i]);
the substring method is apparently causing the problem because indexOf returns -1 if the . isn't found.
In this case, though, the code actually isn't the problem, since the assignment states that you can assume that the file names are of the form <source-name>.corpus. That being said, really, all of the command line parameters should have a . in them, so this shouldn't be happening.
I'd check to see what command line parameters you're passing. One guess I have is that you might have a file name with a space in it or something. For example, if you passed English GB.corpus, then this would show up as 2 separate arguments (one of which doesn't have a .).
Edit: As #Pshemo pointed out in the comments, if you have a file name that has a space in it, you can just put it in quotes so that it'll be interpreted as a single command line parameter - for example, instead of English GB.corpus, write "English GB.corpus". That'll prevent the exception.
In your main method, you have:
args[i].indexOf(".")
The dot (.) is not found so it returns -1.
You try to create a substring:
models[i] = new SourceModel(args[i].substring(0, args[i].indexOf(".")), args[i]);
But since args[i].indexOf(".") is invalid, it throws an exception.
What you can do is check if the dot (.) exists, if yes continue:
if(args[i].contains(".")){
models[i] = new SourceModel(args[i].substring(0, args[i].indexOf(".")), args[i]);
}
Related
I'm working on Boyer Moore string matching algorithm in java so it could work on Arabic text sufficiently, I have the code that finds the first occurrence of a pattern instead of all occurrence.
I tried to modify to it but it doesn't work, I got arrayIndexoutofbounds exception.
the exception I got is :
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException:
-1 at BM.findPattern(BM.java:27) at BM.main(BM.java:110)
the purpose is to modify the algorithm so it can handle the vocalized Arabic Text.
here is a sample of input and out put:
Enter Text
anananananana
Enter Pattern
ana
found at postion 0
then I got the exception above
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.IOException;
/** Class BoyerMoore **/
public class BM
{
/** function findPattern **/
public void findPattern(String t, String p)
{
char[] text = t.toCharArray();
char[] pattern = p.toCharArray();
int pos = indexOf(text, pattern);
if (pos == -1)
System.out.println("\nNo Match\n");
else
System.out.println("Pattern found at position : "+ pos);
}
/** Function to calculate index of pattern substring **/
public int indexOf(char[] text, char[] pattern)
{
if (pattern.length == 0)
return 0;
int charTable[] = makeCharTable(pattern);
int offsetTable[] = makeOffsetTable(pattern);
for (int i = pattern.length - 1, j; i < text.length;)
{
for (j = pattern.length - 1; pattern[j] == text[i]; --i, --j)
if (j == 0)
return i;
// i += pattern.length - j; // For naive method
i += Math.max(offsetTable[pattern.length - 1 - j],
charTable[text[i]]);
}
return -1;
}
/** Makes the jump table based on the mismatched character
information **/
private int[] makeCharTable(char[] pattern)
{
final int ALPHABET_SIZE = 256;
int[] table = new int[ALPHABET_SIZE];
for (int i = 0; i < table.length; ++i)
table[i] = pattern.length;
for (int i = 0; i < pattern.length - 1; ++i)
table[pattern[i]] = pattern.length - 1 - i;
return table;
}
/** Makes the jump table based on the scan offset which mismatch
occurs. **/
private static int[] makeOffsetTable(char[] pattern)
{
int[] table = new int[pattern.length];
int lastPrefixPosition = pattern.length;
for (int i = pattern.length - 1; i >= 0; --i)
{
if (isPrefix(pattern, i + 1))
lastPrefixPosition = i + 1;
table[pattern.length - 1 - i] = lastPrefixPosition - i +
pattern.length - 1;
}
for (int i = 0; i < pattern.length - 1; ++i)
{
int slen = suffixLength(pattern, i);
table[slen] = pattern.length - 1 - i + slen;
}
return table;
}
/** function to check if needle[p:end] a prefix of pattern **/
private static boolean isPrefix(char[] pattern, int p)
{
for (int i = p, j = 0; i < pattern.length; ++i, ++j)
if (pattern[i] != pattern[j])
return false;
return true;
}
/** function to returns the maximum length of the substring ends at p and is a suffix **/
private static int suffixLength(char[] pattern, int p)
{
int len = 0;
for (int i = p, j = pattern.length - 1; i >= 0 && pattern[i] == pattern[j]; --i, --j)
len += 1;
return len;
}
/** Main Function **/
public static void main(String[] args) throws IOException
{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
System.out.println("Boyer Moore Algorithm Test\n");
System.out.println("\nEnter Text\n");
String text = br.readLine();
System.out.println("\nEnter Pattern\n");
String pattern = br.readLine();
BM bm = new BM();
bm.findPattern(text, pattern);
}
}
I have a 2D Array map[6][6] and the values are randomly generated in a for loop
This is what the output looks like (In integer values)
There are 5 different brick colors
I want to be able to check for 3-6 of the same brick color in a row (Horizontally and Vertically) when they are randomly generated, and when the user changes a brick value
I am also fairly new to Java (3 Months or so) so I would like a simple way to do this (I do not know things like objects)
Sorry for the delay John. Holiday stuff to do and guests. It's that time of year. :)
In any case. I quickly developed two run-able classes you can use to play with a method you have actually named. It's called the hasThreeInSix() even though it's not limited to any three or six that's the name we're going to give it.
Even though it's specifically designed for 2D integer Arrays it wouldn't take much effort to modify it for whatever.
The first run-able below is for testing only. It simply shows you what is going on via the output console (pane)
The second run-able is is what you may want to apply to carry out your task. Take a close look at your randomBoard() method so that you can see how we've used the hasThreeInSix() method.
Here is the code for the run-able Test Class:
import java.util.ArrayList;
import java.util.Scanner;
public class TESTThreeAndSixMethod {
public static void main(String[] args) {
Scanner userInput = new Scanner(System.in);
String input = "";
while (!input.equals("quit")) {
Echo("\nPress ENTER to generate random number blocks\n"
+ "for 2 dimensional array or enter 'quit' to exit:");
input = userInput.nextLine();
if (input.toLowerCase().equals("quit")) { System.exit(0); }
int[][] x = new int[6][6];
randomBoard(x);
}
userInput.close();
}
public static void randomBoard (int[][] x) {
int[][] map = new int[6][6];
Echo("");
for (int i = 0 ; i < x.length ; i++) {
String arrayString = "";
for (int j = 0 ; j < x[i].length ; j++) {
int tmp = 1 + (int) (Math.random () * 5);
map[i][j] = tmp;
arrayString+= String.valueOf(map[i][j]);
}
// Play with the maxHorizontal, maxVertical, and numberToCheckFor
// parameters. What you see here now will never allow any array
// row of elements contain 3 of any same consecutive single digit
// values either horizontally of vertically. Nowhere should there
// ever be any three of the same digits either vertically or hor-
// zontally. If you just want to deal with a specific number from
// 0 to 9 then change the -1 to that number.
String result = hasThreeInSix(map, i, 3, 3, -1);
if (!"".equals(result)) {
Echo(arrayString + " -- " + result);
//i--;
}
else { Echo(arrayString); }
}
}
/**
* Detect specified same single digit elements either or horizontally and or vertically within
* a 2D Array. This method is to be used during the creation of the 2D Array so as to eliminate
* specified same elements from being placed into the Array.<br><br>
*
* #param array (Integer 2D Array) the array being created.<br>
*
* #param currentIndexRow (Integer) The most currently added ROW index number.<br>
*
* #param maxHorizontal (Integer) The number of same digit elements to detect horizontally. If
* 0 is supplied then no horizontal check is done. 1 can not be supplied. If it is then the method
* simply returns null string which ultimately indicates that the array row is good. 1 is not
* permitted because this will just lead to a infinite loop.<br>
*
* #param maxVertical (Integer) The same number of digit elements to detect vertically. If 0 is
* supplied then no Vertical check is done. 1 can not be supplied. If it is then the method simply
* returns null string which ultimately indicates that the array row is good. 1 is not permitted
* because this will just lead to a infinite loop.<br>
*
* #param numberToCheckFor (Integer) The number to check for to see if there is a repetitive
* sequence horizontally or vertically within the Array. Any single digit number from 0 to 9
* can be suppled. If -1 is supplied then this method will check for repetitive sequences for
* ALL numbers from 0 to 9 both horizontally and vertically.<br>
*
* #return (String) If a null string ("") is returned then this indicates that the Array Row is
* good. If a vertical and or horizontal sequence is detected then a string is returned indicating
* either the row sequence value for horizontal detection or the rows and columns detected for
* vertical detection.
*/
public static String hasThreeInSix(int[][] array, int currentIndexRow, int maxHorizontal,
int maxVertical, int numberToCheckFor) {
String indexString = "";
int n = 1, check = numberToCheckFor;
if (maxHorizontal > 0) {
// Check for horizontal values...
String aStrg = "";
if (maxHorizontal < 2 || maxVertical < 2) {
Echo("\n\u001B[31mmaxHorizontal and or maxVertical Parameter Error!\n"
+ "\u001B[34mNeither of these parameters can be less than 2\n"
+ "otherwise an infinite loop will occure! Exiting Method!\u001B[39;49m");
return "";
}
for (int i = 0; i < array[currentIndexRow].length; i++) {
aStrg+= array[currentIndexRow][i];
}
if (numberToCheckFor == -1) { n = 10; }
for (int c = 0; c < n; c++) {
String valToCheckFor = "";
if (numberToCheckFor == -1) { check = c; }
for (int i = 1; i <= maxHorizontal; i++) {
valToCheckFor+= String.valueOf(check);
}
if (aStrg.contains(valToCheckFor)) { return "Horizontal " + maxHorizontal + " Detected! (" + aStrg + ")"; }
}
}
if (maxVertical > 0) {
// Check for vertical values...
ArrayList<String> listString = new ArrayList<>();
for (int i = 0 ; i < array.length ; i++) {
String aString = "";
for (int j = 0 ; j < array[i].length ; j++) {
aString+= String.valueOf(array[i][j]);
}
if (!"000000".equals(aString)) { listString.add(aString); }
}
n = 1; check = numberToCheckFor;
if (numberToCheckFor == -1) { n = 10; }
for (int c = 0; c < n; c++) {
if (numberToCheckFor == -1) { check = c; }
String itemToLocate = String.valueOf(check);
String foundInfo = "";
for (int i = 0; i < listString.get(0).length(); i++) {
int counter = 0;
for (int j = 0; j < listString.size(); j++) {
if (listString.get(j).substring(i,i+1).equals(itemToLocate)) {
if ("".equals(foundInfo)) { foundInfo = "Vertical " + maxVertical + " Detection in Column " + (i+1) + " On Rows: -> " + (j+1); }
else { foundInfo+= ", " + (j+1); }
counter++;
}
else {counter = 0; foundInfo = ""; }
if (counter == maxVertical) {
indexString = foundInfo;
break;
}
}
if (!"".equals(indexString)) { break; }
}
if (!"".equals(indexString)) { break; }
}
}
return indexString;
}
private static void Echo(Object object) {
System.out.println(object);
}
}
And here is the code for the runable class which contains the workable hasThreeInSix() method:
import java.util.ArrayList;
import java.util.Scanner;
public class ThreeAndSixMethod {
public static void main(String[] args) {
Scanner userInput = new Scanner(System.in);
String input = "";
while (!input.equals("quit")) {
Echo("\nPress ENTER to generate random number blocks\n"
+ "for 2 dimensional array or enter 'quit' to exit:");
input = userInput.nextLine();
if (input.toLowerCase().equals("quit")) { System.exit(0); }
int[][] x = new int[6][6];
randomBoard(x);
}
userInput.close();
}
public static void randomBoard (int[][] x) {
int[][] map = new int[6][6];
Echo("");
for (int i = 0 ; i < x.length ; i++) {
String arrayString = "";
for (int j = 0 ; j < x[i].length ; j++) {
int tmp = 1 + (int) (Math.random () * 5);
map[i][j] = tmp;
// you can remove the line below if you don't want to
// display anything in output.
arrayString+= String.valueOf(map[i][j]);
}
// Play with the maxHorizontal, maxVertical, and numberToCheckFor
// parameters. What you see here now will never allow any array
// row of elements contain 3 of any same consecutive single digit
// values either horizontally of vertically. Nowhere should there
// ever be any three of the same digits either vertically or hor-
// zontally. If you just want to deal with a specific number from
// 0 to 9 then change the -1 to that number.
String result = hasThreeInSix(map, i, 3, 3, -1);
if (!"".equals(result)) { i--; }
// You can remove the else{} line below if you
// don't want to display anything in output.
else { Echo(arrayString); }
}
}
/**
* Detect specified same single digit elements either or horizontally and or vertically within
* a 2D Array. This method is to be used during the creation of the 2D Array so as to eliminate
* specified same elements from being placed into the Array.<br><br>
*
* #param array (Integer 2D Array) the array being created.<br>
*
* #param currentIndexRow (Integer) The most currently added ROW index number.<br>
*
* #param maxHorizontal (Integer) The number of same digit elements to detect horizontally. If
* 0 is supplied then no horizontal check is done. 1 can not be supplied. If it is then the method
* simply returns null string which ultimately indicates that the array row is good. 1 is not
* permitted because this will just lead to a infinite loop.<br>
*
* #param maxVertical (Integer) The same number of digit elements to detect vertically. If 0 is
* supplied then no Vertical check is done. 1 can not be supplied. If it is then the method simply
* returns null string which ultimately indicates that the array row is good. 1 is not permitted
* because this will just lead to a infinite loop.<br>
*
* #param numberToCheckFor (Integer) The number to check for to see if there is a repetitive
* sequence horizontally or vertically within the Array. Any single digit number from 0 to 9
* can be suppled. If -1 is supplied then this method will check for repetitive sequences for
* ALL numbers from 0 to 9 both horizontally and vertically.<br>
*
* #return (String) If a null string ("") is returned then this indicates that the Array Row is
* good. If a vertical and or horizontal sequence is detected then a string is returned indicating
* either the row sequence value for horizontal detection or the rows and columns detected for
* vertical detection.
*/
public static String hasThreeInSix(int[][] array, int currentIndexRow, int maxHorizontal,
int maxVertical, int numberToCheckFor) {
String indexString = "";
int n = 1, check = numberToCheckFor;
if (maxHorizontal > 0) {
// Check for horizontal values...
String aStrg = "";
if (maxHorizontal < 2 || maxVertical < 2) {
Echo("\n\u001B[31mmaxHorizontal and or maxVertical Parameter Error!\n"
+ "\u001B[34mNeither of these parameters can be less than 2\n"
+ "otherwise an infinite loop will occure! Exiting Method!\u001B[39;49m");
return "";
}
for (int i = 0; i < array[currentIndexRow].length; i++) {
aStrg+= array[currentIndexRow][i];
}
if (numberToCheckFor == -1) { n = 10; }
for (int c = 0; c < n; c++) {
String valToCheckFor = "";
if (numberToCheckFor == -1) { check = c; }
for (int i = 1; i <= maxHorizontal; i++) {
valToCheckFor+= String.valueOf(check);
}
if (aStrg.contains(valToCheckFor)) { return "Horizontal " + maxHorizontal + " Detected! (" + aStrg + ")"; }
}
}
if (maxVertical > 0) {
// Check for vertical values...
ArrayList<String> listString = new ArrayList<>();
for (int i = 0 ; i < array.length ; i++) {
String aString = "";
for (int j = 0 ; j < array[i].length ; j++) {
aString+= String.valueOf(array[i][j]);
}
if (!"000000".equals(aString)) { listString.add(aString); }
}
n = 1; check = numberToCheckFor;
if (numberToCheckFor == -1) { n = 10; }
for (int c = 0; c < n; c++) {
if (numberToCheckFor == -1) { check = c; }
String itemToLocate = String.valueOf(check);
String foundInfo = "";
for (int i = 0; i < listString.get(0).length(); i++) {
int counter = 0;
for (int j = 0; j < listString.size(); j++) {
if (listString.get(j).substring(i,i+1).equals(itemToLocate)) {
if ("".equals(foundInfo)) { foundInfo = "Vertical " + maxVertical + " Detection in Column " + (i+1) + " On Rows: -> " + (j+1); }
else { foundInfo+= ", " + (j+1); }
counter++;
}
else {counter = 0; foundInfo = ""; }
if (counter == maxVertical) {
indexString = foundInfo;
break;
}
}
if (!"".equals(indexString)) { break; }
}
if (!"".equals(indexString)) { break; }
}
}
return indexString;
}
private static void Echo(Object object) {
System.out.println(object);
}
}
I hope this helps.
I am writing program which generates Vampire numbers https://en.wikipedia.org/wiki/Vampire_number.
I have main function with numberOfDigits argument, which must be even. If numberOfDigits is equal 4, then we are searching Vampire Numbers in range 1000 to 9999 - four digits. If numberOfDigits is equal 6, then we are searching Vampire Numbers from 100000 to 999999 - which is six digits.
In following file, when I want to search Vampire numbers in range of 10 digits, Java heap space is screaming. Note that I have default settings for memory. But for, numberOfDigits == 4, 6 or 8, code is working correctly. (compared output to https://oeis.org/A014575/b014575.txt , https://oeis.org/A014575 ). So I want to ask,
What I can do to optimize this code? I have thought about using String with digits inside, instead of long/BigInteger. I want to "omit" that heap problem. Saving big numbers to file would be too slow, am I right?
My mate wrote (bigNum.cpp) http://pastebin.com/0HHdE848 - class in C++, to operate on big numbers. Maybe with help from community I could implement that in my a.java? More important - would it be useful for my problem?
edit: My goal is to generate free range of Vampire Numbers, like 4,6,8 - a.java it can do it, even more (if I can bypass heap space problem). And that is when my questions to help comes.
a.java (permutation code from johk95, https://stackoverflow.com/a/20906510 )
import java.util.ArrayList;
import java.util.Arrays;
/**
*
* #author re
*/
public class a {
/**
*
* #param numberOfDigits {int}
* #return ArrayList of Integer
*/
public ArrayList<Integer> vdf(int numberOfDigits) {
if ((numberOfDigits % 2) == 1) {
//or throw Exception of unrecognised format/variable?
System.out.println("cant operate on odd argument");
return new ArrayList<>();
}
long maxRange = 9;
for (int i = 1; i < numberOfDigits; i++) {
maxRange *= 10;
maxRange += 9;
}//numberOfDigits==4 then maxRange==9999, nOD==5 then maxRange==99999,..
long minRange = 1;
for (int i = 1; i < numberOfDigits; i++) {
minRange *= 10;
}//nOD==4 then minRange==1000, nOD==5 then minRange==10000, ..
ArrayList<Integer> ret = new ArrayList<>();
for (long i = minRange; i < maxRange; i++) {
long a = i;
long[] b = new long[numberOfDigits];
for (int j = numberOfDigits-1; j >= 0 ; j--) {
long c = a % 10;
a = a / 10;
b[j] = c;
}
int x = 0;
int y = 0;
ArrayList<long[]> list = permutations(b);
b = null; //dont need now
for(long[] s : list) {
for (int j = 0; j < numberOfDigits/2; j++) {
x += s[(numberOfDigits/2)-j-1] * Math.pow(10, j);
y += s[numberOfDigits-j-1] * Math.pow(10, j);
}
StringBuilder builder = new StringBuilder();
for (long t : s) {
builder.append(t);
}
String v = builder.toString();
if ((v.charAt((v.length()/2)-1) != '0'||
v.charAt(v.length()-1) != '0') &&
x * y == i) {
ret.add(x);
ret.add(y);
System.out.println(x*y+" "+x+" "+y);
break;
}
x = y = 0;
}
}
System.out.printf("%d vampire numbers found\n", ret.size()/2);
return ret;
}
/**
*
*#return vdf(4)
*/
public ArrayList<Integer> vdf() {
return vdf(4);//without trailing zeros
}
/* permutation code copied from
* johk95
* https://stackoverflow.com/a/20906510
*/
private static ArrayList<long[]> permutations(long[] lol) {
ArrayList<long[]> ret = new ArrayList<>();
permutation(lol, 0, ret);
return ret;
}
private static void permutation(long[] arr, int pos, ArrayList<long[]> list){
if(arr.length - pos == 1)
list.add(arr.clone());
else
for(int i = pos; i < arr.length; i++){
swap(arr, pos, i);
permutation(arr, pos+1, list);
swap(arr, pos, i);
}
}
private static void swap(long[] arr, int pos1, int pos2){
long h = arr[pos1];
arr[pos1] = arr[pos2];
arr[pos2] = h;
}
public static void main(String[] args) {
a a = new a();
try{
a.vdf(10); //TRY IT WITH 4, 6 or 8. <<<<
}catch (java.lang.OutOfMemoryError e){
System.err.println(e.getMessage());
}
}
}
EDIT: http://ideone.com/3rHhep - working code above with numberOfDigits == 4.
package testing;
import java.util.Arrays;
public class Testing
{
final static int START = 11, END = 1000;
public static void main(String[] args)
{
char[] kChar, checkChar;
String kStr, checkStr;
int k;
for(int i=START; i<END; i++) {
for(int i1=i; i1<100; i1++) {
k = i * i1;
kStr = Integer.toString(k);
checkStr = Integer.toString(i) + Integer.toString(i1);
//if(kStr.length() != 4) break;
kChar = kStr.toCharArray();
checkChar = checkStr.toCharArray();
Arrays.sort(kChar);
Arrays.sort(checkChar);
if(Arrays.equals(kChar, checkChar)) {
System.out.println(i + " * " + i1 + " = " + k);
}
}
}
}
}
This will generate vampire numbers, just modify the start and end integers.
I'm trying to erase every X in a .txt file. When a coordinate is chosen, if it is an X is should be replaced with a 0 then also every X that is touching it (except diagonally) should be replaced until there are no more X's that can be touched. I'm not getting these results with my current code.
I'm getting this error java.lang.ArrayIndexOutOfBoundsException: 9 when I input in 0 for getCoord(grid.length, "row") and 2 for getCoord(grid[0].length, "column") in main().
thank you for your help.
image1.txt
00X000000
0XXXXXXX0
0X00000XX
0X0X000XX
0X00000X0
0XXXXXXX0
XXXX00XX0
000XX0000
eraseImage.java
import java.io.*;
import java.util.StringTokenizer;
/**
* eraseImage.java
*
* Your Name Goes Here!
*
* will dimension and load a 2-dimensional array of Strings
* from a text file. The first line of the file will contain
* the dimensions of the grid. Each additional line will have
* String made up of 'X's and '0's (that's zeros) to represent
* part of an image (X) or a non-image cell(0).
*/
public class eraseImage
{
public static void main(String[] args) throws IOException
{
String[][] grid = load();
display(grid);
do
{
int targetRow = getCoord(grid.length, "row");
int targetCol = getCoord(grid[0].length, "column");
rubOut(grid, targetRow, targetCol);
display(grid);
}
while(again());
}
/**
* Please provide documentation here
*/
public static String[][] load() throws IOException
{
BufferedReader innie = new BufferedReader(new FileReader("/Users/laxgoalie1996/Desktop/image1.txt"));
String str = innie.readLine();
StringTokenizer tokens = new StringTokenizer(str);
int rows = Integer.parseInt(tokens.nextToken());
int cols = Integer.parseInt(tokens.nextToken());
String[][] image = new String[rows][cols];
for(int row = 0; row < rows; row++)
{
str = innie.readLine();
for(int col = 0; col < str.length(); col++)
image[row][col] = str.substring(col, col+1);
System.out.println(str);
}
return image;
}
/**
* Please provide documentation here
*/
public static void display(String[][] g)
{
System.out.println("\nHere is the current image...\n");
for (int row = 0; row < g.length; row++) {
for (int column = 0; column < g[row].length; column++) {
System.out.print(g[row][column] + " ");}
System.out.println();}
System.out.println();
}
/**
* Please provide documentation here
*/
public static void rubOut(String[][] g, int tRow, int tCol)
{
String str = g[tRow][tCol];
System.out.println(str);
if(str.equals("0"))
return;
g[tRow][tCol] = "0";
rubOut(g, tRow, tCol + 1);
rubOut(g, tRow, tCol - 1);
rubOut(g, tRow + 1, tCol);
rubOut(g, tRow - 1, tCol);
return;
}
/**
* Please provide documentation here
*/
public static int getCoord(int max, String prompt)
{
java.util.Scanner scan = new java.util.Scanner(System.in);
System.out.print("Enter the " + prompt + " number (0 to " + (max-1) + ") -> ");
int coord = scan.nextInt();
while(coord < 0 || coord >= max)
{
System.out.print("HEY! The " + prompt + " number needs to be between 0 and " + (max-1) + " -> ");
coord = scan.nextInt();
}
return coord;
}
/**
* Please provide documentation here
*/
public static boolean again()
{
return false;
}
}
You need to add bounds checks to your rubOut function:
public static void rubOut(String[][] g, int tRow, int tCol)
{
if((tRow < 0) || (tRow >= g.length))
return;
if((tCol < 0) || (tCol >= g[tRow].length))
return;
...
}
Even though your initial indices of row = 0 and column = 2 are within bounds, you are going to go out of bounds when you call rubOut(g, tRow - 1, tCol); because tRow will then be -1.
Use this for loop for replace X over 0
public static void main(String [] args){
String[][] str ={{"0","0","X","0","0","0","0","0","0"},
{"0","X","X","X","X","X","X","X","0"},{"0","X","0","0","0","0","0","X","X"},
{"0","X","0","X","0","0","0","X","X"},{"0","X","0","0","0","0","0","X","0"},};
for (int i=0; i<str.length; i++) {
for(int j=0; j<str[i].length; j++){
System.out.print(str[i][j]);
}
System.out.println();
}
System.out.println();
for (int i=0; i<str.length; i++) {
for(int j=0; j<str[0].length; j++){
if(i==j){
str[i][j]="0";
}
System.out.print(str[i][j]);
}
System.out.println();
}
}
This will replace X over 0
When I run the code below, why does it throw this error?
Exception in thread "main" java.util.InputMismatchException
at java.util.Scanner.throwFor(Scanner.java:840)
at java.util.Scanner.next(Scanner.java:1461)
at java.util.Scanner.nextInt(Scanner.java:2091)
at java.util.Scanner.nextInt(Scanner.java:2050)
at GuessNumber.main(GuessNumber.java:35)
This is my code, thank you:
public class GuessNumber {
public static void main(String[] args) {
int[][] num = new int[5][16];
int[] len = new int[5];
char[] bit;
for (int i = 1; i <= 32; i++) {
bit = ToBinary(i);
//bit的大小为5:把二进制数存储到数组中num
for (int j = 0; j < bit.length; j++) {
if (bit[j] == '1') {
//11000
num[j][len[j]++] = i;
}
}
}
Random r = new Random((new Date()).getTime());
int numRoad = r.nextInt(31);
bit = ToBinary(numRoad);
String cardRand = "";
for (int i = 0; i < bit.length; i++) {
if (bit[i] == '1') {
cardRand = cardRand + (i + 1) + ",";
}
}
System.out.println("在卡片" + cardRand + "上的数字是:");
System.out.println("请玩家输入猜测数字:");
Scanner c = new Scanner(System.in);
int number = c.nextInt();
if (number == numRoad) {
System.out.println("恭喜您,猜对了.");
} else {
System.out.println("对不起!猜错了,该数应该为:" + numRoad);
}
}
/**
* 将十进制数转成二进制数
*
* #param i
* #return
*/
public static char[] ToBinary(int c) {
char[] bit = new char[5];
String a = Integer.toBinaryString(c);
bit = a.toCharArray();
char temp;
for (int i = 0; i < bit.length / 2; i++) {
temp = bit[i];
bit[i] = bit[bit.length - 1 - i];
bit[bit.length - 1 - i] = bit[i];
}
return bit;
}
}
Most likely because the Scanner expected an integer value and found something else. The exception is a result of your actual input at the console.
Looks like you see a binary number (10011) and have to enter the decimal value (19)
Javadoc to the rescue:
Throws:
InputMismatchException - if the next token does not match the
Integer regular expression, or is out of range
You probably don't enter a valid integer whan asked for it by your program.