Printing letters in 2D arrays? First letter not showing - java

I'm hoping someone can answer this so I'll try to explain this well.
My goal is to generate a MAXIMUM of 3 unique vowels (AEIOU) on a line of 5 squares. I have made 25 squares using a 2D array (board[][]), but I want to do the first line first. Picture it like this:
Now, my problem is, whenever I try to generate random letters in my squares, the first letter doesn't show. For example I have E and O, O would only show in my squares, and not E. It's printing in my console, but not in my GUI.
Also, sometimes DUPLICATES of letters are showing. I don't know how to fix this :|
Here are the codes I've done so far:
String board[][] = new String[5][5];
String alphabet = "AEIOU";
int numArray[] = new int[5]; //where I can store random indices of alphabet
int finalIndex = 0;
int random = (int) (Math.random()*3) + 1; //random number of vowels to be generated
//this loop covers everything
for(int ctr = 0; ctr < random; ctr++) {
while(ctr != finalIndex) { //checks if there are any duplicates
int rand = (int) (Math.random()*4); //random position for the letter
numArray[ctr] = rand;
while(numArray[ctr] != numArray[finalIndex]) {
finalIndex++;
}
}
//finds the position of the letter in alphabet and converts it to String
char character = alphabet.charAt(numArray[ctr]);
String s = String.valueOf(character);
System.out.println(s);
//loop for putting the letters to the 2D array
for(int i = 0; i < board.length; i++) {
int gen = (int) (Math.random()*4); //random square for letter
for(int j = 0; j <= gen; j++) {
if(i == 0 && j < 5) { //row 1
board[i][gen] = s;
}
}
}
}
I decided not to put my GUI code anymore just to make things simpler.

Sorry I couldn't read what you had, so i tried this myself...
int rows = 5;
Character [] vowels = {'A','E','I','O','U'};
Character [][] board = new Character [vowels.length][rows];
for(int row = 0;row<rows;row++){
ArrayList<Character> tempVowels = new ArrayList<Character>(Arrays.asList(vowels));
int numVowPerLine = (int)Math.floor(Math.random()*4);
for(int j = 0;j<numVowPerLine;j++){
do{
int pos = (int)Math.floor(Math.random()*5);
if(board[row][pos] == null){
int temp = (int)Math.floor(Math.random()*tempVowels.size());
board[row][pos] = tempVowels.get(temp);
tempVowels.remove(temp);
break;
}
}while(true);
}
}

Related

I don't know how assign new value to the empty array

I am a beginner in coding. I have to write a code that will divide array with random numbers into two different arrays. One array will contain odd numbers, the other one even numbers. But something is wrong, and i don't really know what to do.
According to the console the problem is in the place where there is a lot of exclamation marks. when i change those lines to System.out.println("x") it works perfectly fine.
public void P_N () {
int I_E = 0; // amount of even numbers
int I_O = 0; // amount of odd numbers
for (int i = 0; i < tab2.length; i++) { // tab2 is a array with random numbers
if (tab2[i] % 2 == 0)
I_E = I_E + 1;
else
I_O = I_O+1;
}
int [] tab_E = new int[I_E]; // array with even numbers
int [] tab_O = new int [I_O]; // array with odd numbers
for (int i = 0; i < tab2.length; i++){
if (tab2[i] % 2 == 0){
tab_E[i] = tab2[i]; //!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
}
}
for (int i = 0; i < tab2.length; i++){
if (tab2[i] % 2 != 0){
tab_O[i] = tab2[i]; //!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
}
}
for (int i = 0; i< tab_E.length; i++) {
System.out.println("Even array: " + tab_E[i]);
System.out.println("------------------------------------------------");
}
for (int i = 0; i< tab_O.length; i++) {
System.out.println("Odd array: " + tab_O[i]);
}
}
Problem is in going out of bounds for arrays tab_E and tab_O, when variable i is more tab_E.length. Just create another variable, for example "j". And iterate throug your array using it. Like I'v written below
int j = 0;
for (int i = 0; i < tab2.length; i++) {
if (tab2[i] % 2 == 0) {
tab_E[j++] = tab2[i];
// !!!!!!!!!!!!!!!!!!!!!!!!!!!!!
}
}
j = 0;
for (int i = 0; i < tab2.length; i++) {
if (tab2[i] % 2 != 0) {
tab_O[j++] = tab2[i];
// !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
}
}
I would rather use 2 ArrayLists one for even numbers and another one is for odd numbers and later convert it into array using toArray() method.
public void P_N(){
ArrayList<Integer> evenNumberList = new ArrayList<Integer>();
ArrayList<Integer> oddNumberList = new ArrayList<Integer>();
for (int i = 0; i < tab2.length; i++) { // tab2 is a array with random numbers
if (tab2[i] % 2 == 0) {
evenNumberList.add(tab2[i]);
} else {
oddNumberList.add(tab2[i]);
}
}
int[] evenNumberArray = evenNumberList.toArray();
int[] oddNumberArray = oddNumberList.toArray();
}
This will take some extra space but makes your application more efficient, I hope this helps.
You have initialized the even/odd number arrays with a quantity of the even/odd numbers accordingly:
int [] tab_E = new int[I_E]; // array with even numbers
int [] tab_O = new int [I_O]; // array with odd numbers
Ii is reasonable to assume that the sizes of even or odd number arrays are might be much smaller than the size of the original source array.
But in this even number filtering loop (as well as in the odd filtering loop) you use source array index values to address target array positions, end eventually face the ArrayIndexOutOfBoundsException.
for (int i = 0; i < tab2.length; i++)
{
if (tab2[i] % 2 == 0)
{
tab_E[i] = tab2[i]; //here the same i value is used to address non existing index in tab_E array
}
}
A quick fix might be the following:
int tab_E_index = 0;
for (int i = 0; i < tab2.length; i++){
if (tab2[i] % 2 == 0){
tab_E[tab_E_index] = tab2[i]; //i value gets incremented every loop iteration
tab_E_index++; //tab_E_index value get incremented only when even number is added to the tab_E array
}
}
Please don't just copy/paste it, but try to understand what caused the issue on the first place. Good luck and happy coding.

Java 2D arrays coin collection game from larger neigbouring cell

My issue is the following:
I have a 2D array of size n x m, entered on a single line. On the next n lines there are m number of elements, that fill the array. So far so good.
There is a pawn on the field that always starts at the only 0 on the field (assuming there is always one 0).
It can move up and down, right and left. It always moves to the neighbouring cell with most coins and at each move collects 1 coin (=> empties the visited cell by 1). The pawn does this until there are only 0s around it and it can collect nothing anymore. I need to find the sum of all coins collected.
Here is a representation of first steps in Paint:
Coin Collection first steps:
Sample input:
4 3, 3 2 4, 2 0 3, 1 1 5, 2 2 5 -> output: 22
Here is my code so far:
I have some unfinished work with the targetCell (I still wonder how to get its coordinates dynamically in a loop, so that each cell with a larger value than the previous turns to a targetCell.) Also I'm stuck with using the directions I just created. Any hints would be useful for me to further develop the task.
Scanner scanner = new Scanner(System.in);
String input = scanner.nextLine();
String[] my_array = input.split(" ");
int[] array = Arrays.stream(my_array).mapToInt(Integer::parseInt).toArray();
int n = array[0]; // rows of matrix
int m = array[1]; // cols of matrix
int[][] matrix = new int[n][m];
for (int i = 0; i < n; i++) {
String line = scanner.nextLine();
String[] numbers = line.split(" ");
matrix[i] = new int[m];
for (int j = 0; j < m; j++) {
matrix[i][j] = Integer.parseInt(numbers[j]);
}
}
int startPoint = 0;
int currentRow = 0;
int currentCol = 0;
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
if (matrix[i][j] == 0) {
startPoint = matrix[i][j];
currentRow = i;
currentCol = j;
}
}
}
int target1 = 0;
int target2 = 0;
int targetCell = 0;
target1 = Math.max(matrix[currentRow - 1][currentCol], matrix[currentRow + 1][currentCol]);
target2 = Math.max(matrix[currentRow][currentCol - 1], matrix[currentRow][currentCol + 1]);
targetCell = Math.max(target1, target2);
System.out.println(targetCell);
int hDirection = 1;
if (targetCol < currentCol) {
hDirection = -1;
}
int vDirection = 1;
if (targetRow < currentRow) {
vDirection = -1;
}
}
}
}
(Can't comment so will use an answer for now. Sorry)
My first thought would be to keep a global variable for the run so that when a coin is collected, it is added to its current value; similar to how you would keep score in games like Tetris. That's assuming I've read it right.
So something like:
private static int current_score = 0; //Assuming no use of objects so using static
Couldn't understand the sample input in this example. If you could give a three turn scenario of what the final score would be, I could give you better insight.

How would I splice and add these two char arrays?

I have this array.
char [] cornStrand = {'G','G','A','G','T','T','C','C','C','A'};
I also have this array, for which the values are inputted by the user running the program.
char [] bacteriaStrand = new char [5];
String strBases = scan.nextLine();
for (int s=0; s <bacteriaStrand.length; s++)
{
char c = strBases.charAt(s);
bacteriaStrand[s]= c ;
}
The second block of code essentially inputs the values that the user entered into the bacteria strand array.
Now comes the tricky part. I need to "splice" and combine both arrays. By this I mean:
If the first character of
char [] bacteriaStrand
is A, then I have to insert
char [] bacteriaStrand
After the first G in
char [] cornStrand
Now, after I splice this, I have to put what I spliced into a new array, called
char [] combinedStrand
This is where I am becoming confused. If anyone can help, please do so! I would gladly appreciate it!
Maybe do something like this:
public char[] combine(char[] bacteriaStrand, char[] cornStrand) {
char[] result = new char[bacteriaStrand.length + cornStrand.length];
if (bacteriaStrand[0] == 'A') {
for (int i = 0; i < cornStrand.length; i++) {
boolean insertedBacteria = false;
if (cornStrand[i] == 'G') {
insertedBacteria = true;
for (int j = 0; j < bacteriaStrand.length; j++) {
result[i + 1 + j] = bacteriaStrand[j];
}
if (insertedBacteria)
i += bacteriaStrand.length;
result[i] = cornStrand[i];
}
}
}
return result;
}
If that is the only rule, it seems pretty simple to do.
if (bacteriaStrand[0] == 'A') {
int totalLength = cornStrand.length + bacteriaStrand.length;
char [] combinedStrand = new char [totalLength];
for(int i=0; i<cornStrand.length; i++){
combinedStrand[i] = cornStrand[i]; //fill in corn until you find the first G
if (cornStrand[i] == 'G') {
int j = 0;
for(; j<bacteriaStrand.length; j++){
combinedStrand[i+j+1] = bacteriaStrand[j]; //fill in bacteria
}
i++;
for(;i<cornStrand.length;i++){
combinedStrand[i+j+1] = cornStrand[i] //fill in the rest of corn
}
}
}//now this loop will break, since you increased i, so you won't get duplicates
}

java.lang.ArrayIndexOutOfBoundsException when I make a string of characters

Ok so I'm trying to generate a random character generator that goes beyond simple numbers and letters. I want to simultaneously create a replica of that same generator for the purpose of comparing them and having it print out how many attempts it took for "Cracker" to match the value of "Generator" because I'm interested in the concept after reading a bit of cryptography. When parsing the characters to a string, I get an OutOfBoundsException, but why? I can't seem to find much on the limitations of string. I would think it would have to been an issue besides the string not being able to take the characters but I can't figure it out.
import java.util.Random;
public class Class {
public static void Generator(){
Random r = new Random();
String[] cArray = new String[10];
for(int i = 0; i <= cArray.length; i++){
char c = (char)(r.nextInt(200) + 'a');
String y = Character.toString(c);
cArray[i] = y;
System.out.print(cArray[i]);
}
}
public static void Cracker(){
Random s = new Random();
String[] bArray = new String[10];
for(int x = 0; x <= bArray.length; x++){
char b = (char)(s.nextInt(100) + 'a');
String z = Character.toString(b);
bArray[x] = z;
System.out.print(bArray[x]);
}
}
public static void main(String[] args) {
Generator();
}
}
Any help would be appreciated.
for (int i = 0; i <= cArray.length; i++)
^^^^
Change to
for (int i = 0; i < cArray.length; i++)
^^^^
In both your for loops.
An array of length n has elements from 0 to n-1 - i.e. array arr of length 3 has elements arr[0], arr[1] & arr[2].

How do I take null spaces out of an array?

I have to make a program that takes duplicate characters from an input array and prints out a new array with all unique characters.
It all works. Except when characters are taken out, it leaves an empty box at the end of that new array.
public class Deleter {
public static void main (String[] args){
Scanner keyboard = new Scanner(System.in);
char[] initialInputArray = new char[15];
System.out.println("How many characters do you wish to enter?");
int size = keyboard.nextInt();
while ( size > initialInputArray.length ) {
System.out.println("Error. Enter smaller number.");
size = keyboard.nextInt();
}
if( initialInputArray.length <= 15) {
for ( int counter = 0; counter < size; counter++ ){
initialInputArray[counter] = keyboard.next().charAt(0);
}
{
}
}
deleteRepeats(initialInputArray, size);
//Comeback to print out array
{
for ( int helloWorld = 0 ; helloWorld < size ; helloWorld ++)
System.out.print( initialInputArray[helloWorld] );
}
}
//"deleteReapets" method begins, looking for repeated user inputs
public static char[] deleteRepeats (char[] methodArray, int sizeTwo) {
if (sizeTwo == 0)
return methodArray;
if (sizeTwo == 1)
return methodArray;
int uniqueCharacter = 1;
//Start at the second entered character.
for (int x = 1; x < sizeTwo; ++x) {
int y;
for (y = 0; y < uniqueCharacter; ++y) {
if (methodArray[x] == methodArray[y]) break; // break if we find duplicate.
}
if (y == uniqueCharacter) {
methodArray[uniqueCharacter] = methodArray[x]; // add
++uniqueCharacter; // increment uniqueCharacter...[0,uniqueCharacter) is still "unique char list"
}
}
while ( uniqueCharacter < sizeTwo ) {
methodArray[uniqueCharacter] = 0;
uniqueCharacter++;
}
return methodArray;
}
}
That empty box is the null characters that you added at the end of the array. You are printing them because you are not adjusting size according to the number of unique characters (which can be less than the input size). Since you aren't creating a new array, you don't need to return a char [] from deleteRepeats. Instead, you can return the number of unique characters. That way, the calling program knows how many to print.
If your assignment requires that deleteRepeats return a char[], then you should allocate a new array that has a length exactly equal to uniqueCharacter, copy the unique characters to it, and return that. The calling program can just print that new (and shorter) array, rather than printing the first size elements of the input.
Probably the easiest way would be to make a new array to the size of your array of chars and then copy all of the chars into that. The problem with arrays is that once they have been initialized they can't be re sized. If your are familiar with arrayLists I would recommend using them. But if not try something like this...
int count = 0;
for(int i = 0; i < initialInputArray.size; i++){
count++;
}
char[] newArray = new char[count];
for(int i = 0; i < count; i++){
newArray[i] = initialInputArray[i];
}
I would suggest using a HashSet to remove duplicates and wrapping your char to Character. Something like this:
public static Character[] deleteRepeats (char[] methodArray){
HashSet<Character> set = new HashSet<Character>();
for(int index = 0; index < methodArray.length; index++){
set.add(methodArray[index]);
}
return set.toArray(new Character[set.size()]);
}
So in your main method, what you would do is something like this:
Character[] charArray = deleteRepeats(methodArray);
for(int index = 0; index < charArray.length; index++){
System.out.println(charArray[index]);
}

Categories