Storing Reverse String in 2D Array - java

I am trying to get the contents of a string, and store it in the last row of my 2D array here is what I have so far:
char[][] square = new char[5][5];
String number = new String("three");
for(int k = number.length() - 1; k >= 0; k--)
{
square[4][k] = number.charAt(k);
}
The output the code is giving me is the string in non reversed order.
Isn't this the logic for reversing a string? All I am doing here is setting the fourth column, and all rows starting at the end of the string to it's value. What am I missing?
Thanks

just walk through the loop by hand.
The first time through, k is 4.
So, square[4][4] is set to the character returned by .charAt(4), which is an 'e'.
then square[4][3] becomes 'e', ... and square[4][0] becomes 't'.
square[4] now reads t,h,r,e,e.
You've basically reversed both ends. Try this:
for (int k = 0; k < number.length(); k++) {
square[4][k] = number.charAt(number.length() - k - 1);
}

Yes, because you're not reversing it. You're setting the same character back again at the same position. If you need it reversed then the logic should be
square[4][number.length() - (k + 1)] = number.charAt(k);

You need a different index beyond square[4][k] when you are also copying the value from number.charAt(k) - that is, you are copying the characters backwards (but into the array also backward). There is no need to call new String(String). You could do
char[][] square = new char[5][5];
String number = "three";
for (int i = 0; i < number.length(); i++) {
int k = number.length() - i - 1;
square[4][k] = number.charAt(i);
}
But I would prefer a StringBuilder and StringBuilder.reverse() myself. Like,
char[][] square = new char[5][5];
String number = "three";
square[4] = new StringBuilder(number).reverse().toString().toCharArray();

Related

Is there a way to initialize a 2d array with other arrays?

I have been given a homework assignment as follows:
Read three sentences from the console application. Each sentence should not exceed 80 characters. Then, copy each character in each input sentence in a [3 x 80] character array.
The first sentence should be loaded into the first row in the reverse order of characters – for example, “mary had a little lamb” should be loaded into the array as “bmal elttil a dah yram”.
The second sentence should be loaded into the second row in the reverse order of words – for example, “mary had a little lamb” should be loaded into the array as “lamb little a had mary”.
The third sentence should be loaded into the third row where if the index of the array is divisible by 5, then the corresponding character is replaced by the letter ‘z’ – for example, “mary had a little lamb” should be loaded into the array as “mary zad azlittze lazb” – that is, characters in index
positions 5, 10, 15, and 20 were replaced by ‘z’. Note that an empty space is also a character, and that the index starts from position 0.
Now print the contents of the character array on the console.
The methods, return types, and parameters in the code below are all specified as required so I cannot change any of that information. I am having trouble initializing the 2d array. The instructions say that the sentences must be loaded into the array already reversed etc. but the parameters of the methods for doing this calls for strings. I assume that means I should read the lines as strings and then call the methods to modify them, then use toCharyArray to convert them before loading them into the 2d array. I don't understand how to initialize the 2D array with the values of the char arrays. Is there some kind of for loop I can use? Another issue is that no processing can be done inside of the main method but in the instructions there is no method that I can call to fill the array.
import java.util.regex.Pattern;
public class ReversedSentence {
public static String change5thPosition(String s){
char[] chars = s.toCharArray();
for (int i = 5; i < s.length(); i = i + 5) {
chars[i] = 'z';
}
String newString = new String(chars);
return newString;
}
public static String printChar2DArray(char[][] arr){
for (int x = 0; x < 3; x++) {
for (int y = 0; y < 80; y++) {
// just a print so it does not make new lines for every char
System.out.print(arr[x][y]);
}
}
return null;
}
public static String reverseByCharacter(String s){
String reverse = new StringBuffer(s).reverse().toString();
return reverse;
}
public static String reverseByWord(String s){
Pattern pattern = Pattern.compile("\\s"); //splitting the string whenever there
String[] temp = pattern.split(s); // is whitespace and store in temp array.
String result = "";
for (int i = 0; i < temp.length; i++) {
if (i == temp.length - 1)
result = temp[i] + result;
else
result = " " + temp[i] + result;
}
return result;
}
public static String truncateSentence(String s){
if (s==null || s.length() <= 80)
return s;
int space = s.lastIndexOf(' ', 80);
if (space < 0)
return s.substring(0, 80);
return s;
}
public static void main(String[] args) {
String sentence1 = ("No one was available, so I went to the movies alone.");
String sentence2 = "Ever since I started working out, I am so tired.";
String sentence3 = "I have two dogs and they are both equally cute.";
char[][] arr = new char[3][80];
arr[0] = reverseByCharacter(sentence1).toCharArray();
arr[1] = reverseByWord(sentence2).toCharArray();
arr[2] = change5thPosition(sentence3).toCharArray();
printChar2DArray(arr);
}
}
The error I am getting is:
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: Index 52 out of bounds for length 52
at ReversedSentence.printChar2DArray(ReversedSentence.java:20)
at ReversedSentence.main(ReversedSentence.java:71)
.enola seivom eht ot tnew I os ,elbaliava saw eno oN
The problem is that in your printChar2DArray method you assume that every array has the length of 80, but that's actually not the case here. In Java, a 2D array is just an array of arrays. So, when you have this: char[][] arr = new char[3][80], you are creating an array of 3 arrays, and each of these arrays has the length of 80 characters. That may seem ok, but in the next lines you reinitialize the 3 arrays with something different entirely.
arr[0] = reverseByCharacter(sentence1).toCharArray();
arr[1] = reverseByWord(sentence2).toCharArray();
arr[2] = change5thPosition(sentence3).toCharArray();
Now none of these arrays has the length of 80. Each of them has the length of the respective string.
You can solve this in 2 ways (depending on how constrained your task actually is).
First, you can copy the string into arrays, instead of assigning the arrays to the results of the toCharArray method. You can achieve this with a simple loop, but I wouldn't recommend this approach, because you will end up with arrays of 80 characters, even if the strings contain less.
String firstSentence = reverseByCharacter(sentence1);
for (int i = 0; i < firstSentence.length(); i++) {
arr[0][i] = firstSentence.charAt(i);
}
Or:
char[] firstSentence = reverseByCharacter(sentence1).toCharArray();
for (int i = 0; i < firstSentence.length; i++) {
arr[0][i] = firstSentence[i];
}
Second, you can drop the assumption of the arrays' lengths in the printChar2DArray method. I recommend this approach, because it makes you code much more flexible. Your printChar2DArray method will then look like this:
public static String printChar2DArray(char[][] arr){
for (int x = 0; x < arr.length; x++) {
for (int y = 0; y < arr[x].length; y++) {
// just a print so it does not make new lines for every char
System.out.print(arr[x][y]);
}
}
return null;
}
You can see that I've substituted numbers with the length field, which can be accessed for any array.
Also, this way you don't need to initialize the inner arrays, because you reinitialize them in the next lines anyway.
char[][] arr = new char[3][];
arr[0] = reverseByCharacter(sentence1).toCharArray();
arr[1] = reverseByWord(sentence2).toCharArray();
arr[2] = change5thPosition(sentence3).toCharArray();
But this approach may not be suitable for your task, because then the sentences could be of any length, and they wouldn't be constained to 80 characters max.
UPDATE - To answer the question in the comment
To print a newline character you can use System.out.println() without parameters. It's better than putting the newline character into the arrays because it's not a logical part of the sentences.
So your for-loop in the printChar2DArray would look like this:
for (int x = 0; x < 3; x++) {
for (int y = 0; y < 80; y++) {
// just a print so it does not make new lines for every char
System.out.print(arr[x][y]);
}
System.out.println();
}

How to Optimise a given problem time complexity?

I have a question which says
Given an input
ababacad
The output should be all the a's should come first together rest characters should follow their sequence as they were originally. i.e.
aaaabbcd
I solved it like below code
String temp="", first="" ;
for(int i=0;i<str.length;i++) {
if(str.charAt(i)!='a')
temp=temp+str.charAt(i);
else
first=first+str.charAt(i);
}
System.out.print(first+temp);
The output matches but it says it is still not optimised. I guess its already order of N complexity. Can it be optimised further.
Optimization here can mean string operations as well as the number of iterations. So, just to be on the safe side, you can implement it using arrays. The time complexity will be O(n) which is the minimum for this problem as you have to check every position for the presence of char 'a'.
String input = "ababacad";
char[] array = input.toCharArray();
char[] modified = new char[array.length];
int a = 0; // index for a
int b = array.length - 1; // index for not a
for (int i = array.length - 1; i >= 0; --i) {
if (array[i] != 'a')
modified[b--] = array[i];
else
modified[a++] = array[i];
}
String output = new String(modified);
System.out.println(output);

How can I create a new instance of array dynamically if my array size is full in java

I am working on a java program. where I have taken an input string and I am putting each char from a string in a 4*4 matrix. If the input string length is small than 16 i.e 4*4 matrix, then I am adding padding '#' char.
But Now, suppose the input string length is more than 16 then I want to create a new array and put remaining chars into it. I can't use a vector, set, map. So How can I code now?
here is some code. key=4.
char[][] giveMeNewArray() {
char[][] matrix = new char[key][key];
return matrix;
}
void putCharIntoMatrix() {
int counter = 0;
char[][] myArray = giveMeNewArray();
System.out.println("myArray: " + myArray);
for (int i = 0; i < key; i++) {
for (int j = 0; j < key; j++) {
if (counter >= inputString.length()) {
myArray[i][j] = '#';
} else {
myArray[i][j] = inputString.charAt(key * i + j);
}
counter++;
}
}
for (int i = 0; i < key; i++) {
for (int j = 0; j < key; j++) {
System.out.print(myArray[i][j] + " ");
}
System.out.println();
}
}
So if I'm understanding this question correctly, you want to create a matrix to hold the characters of an input string, with a minimum size of 4*4?
You're probably better off creating a proper matrix rather than expanding it:
Do you want your matrix to always be square?
Get the next-highest (self-inclusive) perfect square using Math.sqrt
int lowRoot = (int)Math.sqrt(inString.length());
int root;
if(lowRoot * lowRoot < inString.length())
root = lowRoot+1;
else
root = lowRoot;
Create your matrix scaled for your input, minimum four
int size = (root < 4) ? 4 : root;
char[][] matrix = new char[size][size];
But if you really want to expand it, you can just create a new matrix of a greater size:
char[][] newMatrix = new char[oldMatrix.length+1][oldMatrix[0].length+1];
And copy the old matrix into the new matrix
for(int i = 0; i < oldMatrix.length; ++i){
for(int j = 0; j < oldMatrix[i].length; ++j){
newMatrix[i][j] = oldMatrix[i][j];
}
}
If you expand by one each time you'll do tons of expands, if you expand by more you might expand too far.
This is really inefficient versus just doing some math at the beginning. Making a properly sized matrix from the start will save you a bunch of loops over your data and regularly having two matrices in memory.
If understand you request correctly, if the string length is bigger than 16 you just create a new array, well how about making a list of array initilized at one array and if there are more than 16 chars just add an array to the list using your method that returns an array.

Converting char array to int array without a loop in Java?

I need to get the binary representation for a range of numbers inside a matrix in order to perform some operations with another vector.
So let's say I will get the binary representation for 2^4 numbers, that's it from 0 to 15. I know I need a 16x4 matrix.
I've got this code:
int [][] a = new int[15][4];
for (int i = 0; i < a.length; i++) {
a[i] = String.format("%5s", Integer.toBinaryString(i)).replace(' ', '0').toCharArray();
}
So, being the array representation of the binary formatted number a char[], I can't just asign it to a[i].
If there any way to perform a cast without looping through the char array?
Not that I am aware of. There are some different ways you can do it, either looping through the integer representation of the binary string, and the taking num%10 and num/10 for every step, if you absolutely don't want a loop through the char array. However in this case it seems pretty straight forward to just loop through the char array. Anyways here is the solution, in the way you didn't want it I guess...
int [][] a = new int[16][4];
for (int i = 0; i < a.length; i++) {
char[] cArr = String.format("%4s", Integer.toBinaryString(i)).replace(' ', '0').toCharArray();
for(int j = 0; j < a[0].length; j++)
a[i][j] = Integer.parseInt(cArr[j]+"");
}
This is a simpler solution to what you are trying to accomplish...
for (int i = 0; i < a.length; i++) {
for (int j = 0; j < a[0].length; j++) {
a[i][a[0].length - 1 - j] = (i & (1 << j)) != 0 ? 1 : 0;
}
}
Instead of converting an integer i to String and then replacing white spaces with zeros and then converting it to array, you:
Take i.
Take a binary number A with the only 1 at j-th position (other being zeros): A = (1 << j)
Perform conjunction (binary bit-wise multiplication) of your number and the number A. This is accomplished by: (i & A)
If there was non-zero bit at that position, after conjunction you will get A. If there was a zero bit, you will get 0.
If the result is not zero, i has non-zero bit in j-th position. Otherwise it has zero there.
The solution using bit-wise operations will be faster too.
I believe that one outer loop will still be required to iterate through char[][] rows.
int[] charArray2intArray(char[][] binary) {
int[] numbers = new int[binary.length];
int row = 0;
for (char[] number: binary) {
String bin = new String(number);
numbers[row++] = Integer.parseInt(bin, 2);
}
return numbers;
}

Counting occurrences of characters in a word list

I'm trying to make an AI for a hangman game, part of which requires counting all occurrences of each possible character in the word list. I'm planning on culling the word list before this counting to make things run faster (by first culling out all words that are not the same length as the guessable phrase, and then by culling out words that do not match the guessed characters).
The problem I am having is in the code below. Somehow, it always returns a list of e's that are the correct length (matching the number of possible characters). I'm not sure exactly what I'm doing wrong here, but the problem is definitely somewhere in countCharacters.
MethodicComputer(){
guessable = parseGuessable();
wordList = parseText();
priorities = countCharacters(guessable);
}
public char guessCharacter(String hint){
char guess = 0;
System.out.println(guessable);
System.out.println(priorities);
guess = priorities.charAt(0);
priorities = priorities.replaceAll("" + guess, "");
return guess;
}
private String countCharacters(String possibleChars){
charCount = new Hashtable();
String orderedPriorities = "";
char temp = 0;
char adding = 0;
int count = 0;
int max = 0;
int length = possibleChars.length();
for (int i = 0; i<length; i++){
temp = possibleChars.charAt(i);
count = wordList.length() - wordList.replaceAll("" + temp, "").length();
charCount.put(temp, count);
}
while (orderedPriorities.length() < length){
for (int i = 0; i < possibleChars.length(); i++){
temp = possibleChars.charAt(i);
if (max < (int) charCount.get(temp)){
max = (int) charCount.get(temp);
adding = temp;
}
}
orderedPriorities += adding;
possibleChars = possibleChars.replaceAll("" + adding, "");
}
return orderedPriorities;
}
The problem is that I did not update the max variable, so it never entered the if statement and updated the adding variable. A simple addition of
max = 0;
to the end of the while loop fixed it.

Categories

Resources