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

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;
}

Related

tictactoe minmax recursion causing confusion

I read a number of tic tac toe examples using the minmax algorithm but haven't found a good one that really explains what's going on. I've written one that works but need help understanding a small section of the recursion process.
If you load the code below, enter your name, O (not zero), and 0 (zero) you'll get the results I'm looking at. After the computer moves stop the program and look at the console.log.
If you look at the console output, you see the line best 0 7 [[0, 7]] that happens just before the return statement. Where is the next line coming from 0 simulateMove = 6 scoreMove[1] = 7 depth = 2
The other question is why on line 423 do I need scoreMoveAvailable[i][1] = simulateMove; instead of scoreMoveAvailable[i][1] = scoreMove[1];
import java.util.Scanner;
import java.util.ArrayList;
import java.util.Random;
import java.util.Arrays;
public class TicTacToeV2{
private static final int boardRowDim = 3;
private static final int boardColDim = 3;
private String[][] board;
private String playerName;
private String playerMark;
private String computerMark;
private boolean humanGoes;
private boolean winner;
private boolean draw
private int gameTargetScore;
private boolean output = true;
private boolean toSeed = true;
private ArrayList<Integer> availableMoves;
public TicTacToeV2(String name, boolean whoGoesFirst){
availableMoves = new ArrayList<Integer>();
board = new String[boardRowDim][boardColDim];
for (int i = 0; i < board.length; i++){
for(int j = 0; j < board[0].length; j++){
board[i][j] = ((Integer)(double2single(i,j))).toString();
availableMoves.add(double2single(i,j));
}
}
playerName = name;
humanGoes = whoGoesFirst;
playerMark = "X";
computerMark = "O";
gameTargetScore = 15;
if(!humanGoes){
playerMark = "O";
computerMark = "X";
gameTargetScore = - 15;
}
winner = false;
draw = false;
}
public static void main(String[] args)throws Exception{
System.out.println("\u000C");
Scanner kboard = new Scanner(System.in);
printHeader();
System.out.print(" Please enter your name ; ");
String name = kboard.next();
name = capitalize(name);
System.out.print("\n\n X's go first. " + name + ", please enter your mark ('X' or 'O')");
String mark = kboard.next().toUpperCase();
boolean whoPlaysFirst = (mark.equals("X")) ? true : false;
TicTacToeV2 myGame = new TicTacToeV2(name,whoPlaysFirst);
myGame.playGame(kboard);
}
public void playGame(Scanner kboard)throws Exception{
Integer move = null;
boolean goodMove;
String kboardInput = null;
Scanner input;
int[] cell2D = new int[2];
Random random = new Random();
int nextComputerMove;
if(toSeed){
board = seedBoard();
availableMoves = seedAvailable(board);
int x = 0;
int o = 0;
for(int i = 0; i < 3;i++){
for(int j = 0;j < 3;j++){
if(board[i][j].equals("X"))x++;
else if(board[i][j].equals("O"))o++;
}
}
if((x - o) == 1) humanGoes = true;
else if((x - o) == 0) humanGoes = false;
else{
System.out.println("Fatal Error: seed bad");
System.exit(0);
}
System.out.println("humangoes = " + humanGoes + x + o);
}
while(!winner && !draw){
printHeader();
goodMove = false;
drawBoard(board);
if(!humanGoes && availableMoves.size() < 9){
System.out.println("That's a great move, I'll have to think about this");
Thread.sleep(2000);
}
if(humanGoes){
while(!goodMove){
System.out.print("\n\n Please enter a number for your move : ");
kboardInput = kboard.next();
input = new Scanner(kboardInput);
if(input.hasNextInt()){
move = input.nextInt();
if(move == 99){
System.out.println("You found the secret exit code");
Thread.sleep(2000);
printHeader();
System.out.println("bye");
System.exit(0);
}
goodMove = checkMove(move);
if(!goodMove)System.out.println(" WARNING: Incorrect input, try again");
}else{
System.out.println(" WARNING: Incorrect input, try again");
}
}
cell2D = single2Double(move);
board[cell2D[0]][cell2D[1]] = playerMark;
}else{
//nextComputerMove = random.nextInt(availableMoves.size());
//move = availableMoves.get(nextComputerMove);
String[][] currentBoard = new String[boardRowDim][boardColDim];
currentBoard = copyBoard(board);
ArrayList<Integer> currentAvailableMoves= new ArrayList<Integer>();
currentAvailableMoves = copyAvailableMoves(availableMoves);
//System.out.println(System.identityHashCode(currentAvailableMoves));
int[] bestScoreMove = new int[2];
bestScoreMove = findBestMove(currentBoard,currentAvailableMoves,true,0,kboard);
move = availableMoves.get(availableMoves.indexOf(bestScoreMove[1]));
cell2D = single2Double(move);
board[cell2D[0]][cell2D[1]] = computerMark;
}
humanGoes = humanGoes ? false:true;
availableMoves = updateAvailableMoves(move,availableMoves);
if (Math.abs(score(board)) == 15) winner = true;
if (availableMoves.size() == 0) draw = true;
if(winner || draw){
printHeader();
drawBoard(board);
}
if(score(board) == gameTargetScore)System.out.println(playerName + " you are too good for me. \n" +
"Congratulations you won!!\n\n");
else if(score(board) == -gameTargetScore)System.out.println("IWONIWONIWONohboyIWONIWONIWON");
else if(draw)System.out.println("Good game. It's a draw!");
}
}
public void drawBoard(String[][] someBoard){
String mark = " ";
Integer row,col;
String type;
for( int i = 0;i < 15; i++){
System.out.print(" ");
for (int j = 0; j < 27; j++){
mark = " ";
if(i==5 || i == 10)mark = "-";
if(j==8 || j == 17)mark = "|";
row = i/5;
col = j/9;
type = someBoard[row][col];
if(type == "X"){
if( ((i%5 == 1 || i%5 == 3) &&
(j%9 == 3 || j%9 == 5)) ||
(i%5 == 2 &&
j%9 == 4))mark = "X";
}else if(type == "O"){
if( ((i%5 == 1 || i%5 == 3) &&
(j%9 == 3 || j%9 == 4 || j%9 == 5)) ||
((i%5 == 2) &&
(j%9 == 3 || j%9 == 5))) mark = "O";
}else{
if( i%5 == 2 && j%9 == 4){
mark = ((Integer)(row * 3 + col)).toString();
}
}
System.out.print(mark);
}
System.out.println();
}
System.out.println("\n\n\n");
}
public boolean checkMove(Integer move){
/*
* to sanitize user input we have to check if what
* they entered is an available square
*/
boolean goodMove = false;
for(Integer available : availableMoves){
if (available == move) goodMove = true;
}
return goodMove;
}
public int score(String[][] newBoard){
int row;
int newCol;
int score = 0;
for (int strategy = 0; strategy < 8; strategy++){
score = 0;
for (int col = 0; col < 3; col++){
if(strategy < 3){ //rows
row = strategy ;
newCol = col;
}else if (strategy < 6){ //cols
row = col;
newCol = strategy - 3;
}else{//diag
int diag = strategy - 6;
row = col - 2 * diag * (col - 1);
newCol = col;
}
if(newBoard[row][newCol].equals("X")){
score+=5;
}else if(newBoard[row][newCol].equals("O")){
score+=-5;
}
}
score = (Math.abs(score)== 15) ? score : 0;
if(Math.abs(score) == 15) break;
}
return score;
}
public String[][] copyBoard(String[][] originalBoard){
String[][] duplicateBoard = new String[boardRowDim][boardColDim];
for (int i = 0;i < boardRowDim; i++){
for(int j = 0; j < boardColDim; j++){
duplicateBoard[i][j] = originalBoard[i][j];
}
}
return duplicateBoard;
}
public String[][] updateBoard(Integer move, String mark, String[][]oldBoard){
String[][] currentBoard = new String[boardRowDim][boardColDim];
int[] cell2D = new int[2];
currentBoard = copyBoard(oldBoard);
cell2D = single2Double(move);
currentBoard[cell2D[0]][cell2D[1]] = mark;
return currentBoard;
}
public ArrayList<Integer> copyAvailableMoves(ArrayList<Integer> originalAvailableMoves){
ArrayList<Integer> duplicateAvailableMoves = new ArrayList<Integer>();
for(int i = 0; i < originalAvailableMoves.size();i++){
duplicateAvailableMoves.add(originalAvailableMoves.get(i));
}
return duplicateAvailableMoves;
}
public ArrayList<Integer> updateAvailableMoves(Integer move, ArrayList<Integer> oldAvailableMoves){
ArrayList<Integer> currentAvailableMoves = new ArrayList<Integer>();
currentAvailableMoves = copyAvailableMoves(oldAvailableMoves);
currentAvailableMoves.remove(move);
return currentAvailableMoves;
}
public String[][] seedBoard(){
String[][] sampleBoard ={{"0","O","X"},{"X","4","O"},{"6","7","X"}};
//String[][] sampleBoard ={{"X","O","O"},{"3","4","X"},{"6","7","8"}};
return sampleBoard;
}
public ArrayList<Integer> seedAvailable(String[][] seedBoard){
ArrayList seedMoves = new ArrayList<Integer>();
int index = -1;
for(int i = 0; i < 3;i++){
for (int j = 0; j < 3; j++){
if(!seedBoard[i][j].equals("X") && !seedBoard[i][j].equals("O")){
index = i*3 + j;
seedMoves.add(index);
}
}
}
//System.out.println(seedMoves);
return seedMoves;
}
public int[] findBestMove(String[][] currentBoard, ArrayList<Integer> currentAvailableMoves,boolean currentComputerMoves,int depth,Scanner kboard){
ArrayList<Integer> simulateAvailableMoves = new ArrayList<Integer>();
String[][] simulateBoard = new String[boardRowDim][boardColDim];
//System.out.println(System.identityHashCode(currentAvailableMoves));
int[] scoreMove = new int[2]; //return array with score and associated move
int[] cell2D = new int[2]; //array holding i and j of board to place Mark (X or O)
int computerTargetScore = (computerMark.equals("X")) ? 15:-15;
/*
* scoreMoveAvailable is an array that holds scores for each available move
* inside loop. The bestScoreMove will be the min or max of this array
* depending on whether it's X's or O's turn to move
*/
int[][] scoreMoveAvailable = new int[currentAvailableMoves.size()][2];
Integer simulateMove = null; //current move inside loop
Boolean simulateComputerMoves = null;
for(int i = 0; i < currentAvailableMoves.size(); i++){
scoreMoveAvailable[i][0] = 0; //score
scoreMoveAvailable[i][1] = -1; // square 0 - 8
}
if(output)System.out.println("on enter available moves " + currentAvailableMoves);
for (int i = 0; i < currentAvailableMoves.size() ;i++){
simulateAvailableMoves = copyAvailableMoves(currentAvailableMoves);
simulateBoard = copyBoard(currentBoard);
simulateComputerMoves = currentComputerMoves;
if(output)System.out.println("in loop available moves " + i + " " + simulateAvailableMoves);
simulateMove = simulateAvailableMoves.get(i);
simulateAvailableMoves = updateAvailableMoves(simulateMove,simulateAvailableMoves);
cell2D = single2Double(simulateMove);
if(simulateComputerMoves){
if(output)System.out.println("computer moves " + simulateMove);
simulateBoard[cell2D[0]][cell2D[1]] = computerMark;
simulateComputerMoves = false;
if(score(simulateBoard) == computerTargetScore || simulateAvailableMoves.size() == 0){
scoreMove[0] = score(simulateBoard);
scoreMove[1] = simulateMove;
if(output)System.out.println("score computer" + Arrays.toString(scoreMove) +" computer moves = " + simulateMove + " i = " + i);
if(output)drawBoard(simulateBoard);
}else{
depth++;
if(output)System.out.println("computer calling findbest " +simulateAvailableMoves);
if(output)drawBoard(simulateBoard);
scoreMove = findBestMove(simulateBoard,simulateAvailableMoves,simulateComputerMoves,depth,kboard);
}
}else{
if(output)System.out.println("human moves" + simulateMove);
simulateBoard[cell2D[0]][cell2D[1]] = playerMark;
simulateComputerMoves = true;
if(score(simulateBoard) == (-computerTargetScore) || simulateAvailableMoves.size() == 0){
scoreMove[0] = score(simulateBoard);
scoreMove[1] = simulateMove;
if(output)System.out.println("score human "+ Arrays.toString(scoreMove) +" human moves " + simulateMove + " i = " + i);
if(output)drawBoard(simulateBoard);
}else{
depth++;
if(output)System.out.println("human calling findbest " + simulateAvailableMoves);
if(output)drawBoard(simulateBoard);
scoreMove = findBestMove(simulateBoard,simulateAvailableMoves,simulateComputerMoves,depth,kboard);
}
}
if(output)System.out.println(i + " simulateMove = " + simulateMove + " scoreMove[1] = " + scoreMove[1] + " depth = " + depth);
// drawBoard(simulateBoard);
scoreMoveAvailable[i][0] = scoreMove[0] ;
scoreMoveAvailable[i][1] = simulateMove;
if(output)System.out.println("score array = " + i + " " + Arrays.deepToString(scoreMoveAvailable));
}
int[] bestScoreMove = new int[2];
bestScoreMove[0] = scoreMoveAvailable[0][0]; //set bestScoreMove to first element in arraylist
bestScoreMove[1] = scoreMoveAvailable[0][1];
if(output)System.out.println("****************************************");
if( (currentComputerMoves && computerMark.equals("X") ) || (!currentComputerMoves && computerMark.equals("O") ) ) {
for (int i = 0; i < scoreMoveAvailable.length;i++){
if(scoreMoveAvailable[i][0] > bestScoreMove[0]){
bestScoreMove[0] = scoreMoveAvailable[i][0] ;
bestScoreMove[1] = scoreMoveAvailable[i][1];
}
if(output)System.out.printf("MAX X scores and moves = %d %d %d %s\n",i,scoreMoveAvailable[i][0],scoreMoveAvailable[i][1],"XXX");
}
if(output)System.out.println("\n");
}else{
for (int i = 0; i < scoreMoveAvailable.length;i++){
if(scoreMoveAvailable[i][0] < bestScoreMove[0]){
bestScoreMove[0] = scoreMoveAvailable[i][0] ;
bestScoreMove[1] = scoreMoveAvailable[i][1];
}
if(output)System.out.printf("MIN O scores and moves =%d %d %d %s\n",i,scoreMoveAvailable[i][0],scoreMoveAvailable[i][1],"OOO");
}
if(output)System.out.println("\n");
}
if(output)System.out.println("best " + bestScoreMove[0] + " " + bestScoreMove[1] + " " + Arrays.deepToString(scoreMoveAvailable));
return bestScoreMove;
}
/*
* just some static methods to help make things easy
*/
public static void printHeader(){
System.out.println("u000C Welcome to TicTacToe\n" +
" where you can match wits\n" +
" against the computer\n" +
"(the real challenge is making it a draw)\n");
}
public static int double2single(int row, int col){
int singleCell = 0;
singleCell = boardRowDim * row + col;
return singleCell;
}
public static int[] single2Double(int cell){
int[] cell2D = new int[2];
cell2D[0] = cell / boardColDim;
cell2D[1] = cell % boardColDim;
return cell2D;
}
public static String capitalize(String word){
word = word.substring(0,1).toUpperCase() + word.substring(1);
return word;
}
}
Note that the below diagram assumes that you are not doing "depth++", but just using "depth + 1" in the recursive call. The former is a benign bug in your code, which leads to printing misleading depths.
findBestMove is first invoked when bestScoreMove = findBestMove... is used to find the computer's move. Based on the seeded board and human taking "0", the moves now available are 4, 6, and 7.
First, the computer simulates moving 4
This creates a recursive call, adding a frame to the function stack. The human now has 6 and 7 as possible moves. Since 6 is first, the human "tries" 6 first. In this simulation now, it's computer/4 -> human/6
Again, a frame is added to the function stack for the recursive call from the human "running a simulation". Now, there's one move left: the computer takes 7. This is where best 0 7 [[0, 7]] is printed.
After the last recursive call returns, the function stack is popped, and we're again where the human is moving 6, and that's where 0 simulateMove = 6.. is printed.
You can use a debugger to show more detailed information about the stack, but here is some extra advice (mostly to make functions shorter) to make it easier to debug:
There's a lot of Thread.sleep(2000); right after a println. You can wrap these two lines in a function
In many but not all places, the logic assumes a board size of 3x3, e.g. && availableMoves.size() < 9). It's inconsistent, and this logic can be confusing. To make it clear, you can create a function "noMovesMade()" that computes this based on the available variables.
Additionally, if(!humanGoes && availableMoves.size() < 9){ can simply go in the "else" block (since that already implies it's the computer's turn)
if((x - o) == 1) humanGoes = true; is assuming that the human is playing "O" when the rest of the code does not assume this.
There are a lot of cases variables are initialized, assigned, and then reassigned without being used. For example, String[][] currentBoard = new String[boardRowDim][boardColDim]; currentBoard = copyBoard(board); is redundant, and the same with bestScoreMove.
Arrays.copyOf can be used to copy arrays (in the inner loop of the copyBoard, for example)
ArrayList.contains can be used instead of iterating through the array in checkMove
humanGoes = humanGoes ? false:true; can be shortened to humanGoes = !humanGoes

[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;

array search and count

I am developing a program that will search through my array for how many times my single random # appears and then print how many times or that it was not found. I have been researching ways to do this and cannot seem to get it figured out. This is what I have so far and thanks in advance.
My code:
import java.util.Scanner;
import java.util.Random;
class Main {
public static final Random RND_GEN = new Random();
public void createNum(int[] randomNumbers) {
for (int i = 0; i < randomNumbers.length; i++) {
randomNumbers[i] = RND_GEN.nextInt(10) + 1;
}
for (int i = 0; i < 1; i++) {
randomNumbers[i] = RND_GEN.nextInt(10) + 1;
}
}
public void printNum(int[] randomNumbers){
for (int i = 0; i < randomNumbers.length; i++) {
System.out.println("Number " + i + " : " + randomNumbers[i]);
}
for (int i = 0; i < 1; i++) {
System.out.println("Single Random # " + i + " : " + randomNumbers[i]);
}
}
public void run() {
Scanner inputReader = new Scanner(System.in);
int x = 1;
do {
int[] number = new int[20];
createNum(number);
printNum(number);
System.out.print("Restart Program?, Enter 1 for YES, 2 for NO: ");
x = inputReader.nextInt();
} while (x == 1);
}
public static void main(String[] args) {
Main go = new Main();
go.run();
}
}
import java.util.Random;
import java.util.Scanner;
public class Main {
private static final Random RND_GEN = new Random();
public int[] createNum(int[] randomNumbers) {
for (int i = 0; i < randomNumbers.length; i++) {
randomNumbers[i] = RND_GEN.nextInt(10) + 1;
}
return randomNumbers;
}
public void printNum(int[] randomNumbers){
for (int i = 0; i < randomNumbers.length; i++) {
System.out.println("Number " + i + " : " + randomNumbers[i]);
}
}
public int findNumInstancesInArray(int[] array, int numLookingFor) {
int count = 0;
for(int i : array) {
if (i == numLookingFor) {
count++;
}
}
return count;
}
public void run() {
Scanner inputReader = new Scanner(System.in);
int x;
do {
int[] numbers = new int[20];
numbers = createNum(numbers);
printNum(numbers);
int numLookingFor = RND_GEN.nextInt(10) + 1;
System.out.println("Number of instances of " + numLookingFor + " is: " + findNumInstancesInArray(numbers, numLookingFor));
System.out.print("Restart Program?, Enter 1 for YES, 2 for NO: ");
x = inputReader.nextInt();
} while (x == 1);
}
public static void main(String[] args) {
Main go = new Main();
go.run();
}
}
This is how you can count an element in an int array:
public int countOccurrences(int[] array, int needle) {
int count = 0;
for (int index = 0; index < array.length; array[++index] == needle ? count++ : count);
return count;
}
It seems as if this is the search part of your other question posted here: Random number and array search
There, you were suggested to learn about linear search and binary search. If you did, it shouldn't be too hard to translate linear search into code (binary search won't help you here). You simply have to loop through the array (you're code proves you know how to do that) and check every value if it equals the one you're searching for. Of course, if you want to count the hits, you have to increase a counter every time the value matches.

Boolean troubles with WordSearch class

Im having difficulty changing my boolean to true, if the word is found.
import java.util.Scanner;
public class WordSearch
{
private char[][] array;
private boolean found;
public WordSearch(char[][] inArray)
{
array = inArray;
}
public void play()
{
Scanner in = new Scanner(System.in);
String choice = "";
while(!choice.equals("end"))
{
print();
System.out.println("What word do you want to search for? (Type end to quit)");
choice = in.nextLine();
System.out.println();
switch (choice)
{
case "end":
break;
default:
search(choice);
break;
}
}
}
public void print()
{
for(int i = 0; i < array.length; i++)
{
for(int j = 0; j < array[0].length; j++)
{
System.out.print(array[i][j]);
}
System.out.println();
}
System.out.println();
}
public void search(String inWord)
{
// Puts inWord into an array
char[] word = new char[inWord.length()];
for(int i = 0; i < inWord.length(); i++)
{
word[i] = inWord.charAt(i);
}
for(int i = 0; i < array.length; i++)// goes to each row
{
for(int j = 0; j < array[0].length; j++)// goes through every letter
{
if(array[i][j] == word[0])// asks if it matches
{
lookHorizantal(word, array, i, j, found);
lookVertical(word, array, i, j, found);
lookDiagnal(word, array, i, j, found);
}
}
}
if(!found)
{
System.out.println(inWord + "was not found!");
}
System.out.println();
}
public void lookHorizantal(char[] inWord, char[][] inArray, int row, int column, boolean ifFound)
{
int counter = 1; //set this to one because we already found the first letter
column += 1;
for(int i = 0; i < inWord.length; i++)
{
if(column < 15 && counter < inWord.length)
{
if(inArray[row][column] == inWord[counter])
{
//System.out.println("WE FOUND A LETTER AT COLUMN: " + row + " Row: " + column);
counter += 1;
column += 1;
}
}
}
if(counter == inWord.length)
{
ifFound = true;
System.out.println(printChar(inWord) + " found horizontally at row " + row + " and column " + (column - counter) + "!");
}
}
public void lookVertical(char[] inWord, char[][] inArray, int row, int column, boolean ifFound)
{
int counter = 1; //set this to one because we already found the first letter
row += 1;
for(int i = 0; i < inWord.length; i++)
{
if(row < 10 && counter < inWord.length)
{
if(inArray[row][column] == inWord[counter])
{
//System.out.println("WE FOUND A LETTER AT COLUMN: " + row + " Row: " + column);
counter += 1;
row += 1;
}
}
}
if(counter == inWord.length)
{
ifFound = true;
System.out.println(printChar(inWord) + " found vertically at row " + (row - counter) + " and column " + column + "!");
}
}
public void lookDiagnal(char[] inWord, char[][] inArray, int row, int column, boolean ifFound)
{
int counter = 1; //set this to one because we already found the first letter
row += 1;
column += 1;
for(int i = 0; i < inWord.length; i++)
{
if(row < 10 && column < 15 && counter < inWord.length)
{
if(inArray[row][column] == inWord[counter])
{
//System.out.println("WE FOUND A LETTER AT COLUMN: " + row + " Row: " + column);
counter += 1;
row += 1;
column +=1;
}
}
}
if(counter == inWord.length)
{
ifFound = true;
System.out.println(printChar(inWord) + " found diagnolly at row " + (row - counter) + " and column " + (column - counter) + "!");
}
}
public String printChar(char[] inChar)
{
String complete = "";
for(int i = 0; i < inChar.length; i++)
{
complete += inChar[i];
}
return complete;
}
}
Every time I find a word it returns false and runs the not found. Am I not declaring the boolean right? or is it resetting when it gets out of a method?
Heres the driver if you want to test it out:
import java.util.*;
import java.io.*;
public class Driver
{
public static void main (String[] args)
{
// try block needed to read in file
try
{
//open the file "sampleSearch.txt"
FileReader fileName = new FileReader("sampleSearch.txt");
Scanner fileRead = new Scanner(fileName);
//read in the number of rows
int numRow = fileRead.nextInt();
fileRead.nextLine();
//read in the number of columns
int numCol = fileRead.nextInt();
fileRead.nextLine();
//create a 2d array to hold the characters in the file
char[][] array = new char[numRow][numCol];
//for each row in the file
for (int r = 0; r < numRow; r++)
{
//read in the row as a string
String row = fileRead.nextLine();
//parse the string into a sequence of characters
for (int c = 0; c < numCol; c++)
{
//store each character in the 2d array
array[r][c] = row.charAt(c);
}
}
//create a new instance of the WordSearch class
WordSearch ws = new WordSearch(array);
//play the game
ws.play();
}
catch (FileNotFoundException exception)
{
//error is thrown if file cannot be found. See directions or email me...
System.out.println("File Not Found");
}
}
}
and heres sampleSearch.txt:
10
15
fqexfecmxdvjlgu
cxomfslieyitqtz
nucatfakuxofegk
hfytpnsdlhcorey
pgrhdqsypyscped
ckadhyudtioapje
yerjodxnqzztfmf
hypmmgoronkzhuo
hdskymmpkzokaao
amuewqvtmrlglad
You cannot modify your immutable primitive boolean (or even a Boolean wrapper) in a called method, changes to the reference will not be preserved outside of the method. Instead, you have two choices -
Store the state in an object field, and provide an accessor for that field (e.g. a getter),
Return boolean (or Boolean) from that method (instead of `void`).
When you pass found as an argument you are passing its value, and not a reference to it, so essentially you are creating a method instance variable.
I would suggest two options
The first would be to return the value:
found = lookHorizantal(word, array, i, j);
// Maybe check between these search calls if it is found?
found = lookVertical(word, array, i, j);
// Maybe check between these search calls
found = lookDiagnal(word, array, i, j);
// Maybe check between these search calls if it is found?
public boolean lookHorizantal(char[] inWord, char[][] inArray, int row, int column)
{
// OMITTED CODE
if(counter == inWord.length)
{
return true; /*******************/
// OMITTED CODE
}
}
or just reference the class variable:
public void lookHorizantal(char[] inWord, char[][] inArray, int row, int column)
{
// OMITTED CODE
if(counter == inWord.length)
{
found = true; /*******************/
// OMITTED CODE
}
}
These switches will change the class variable found directly.

java recurrsion with ArrayList not working

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.

Categories

Resources