rotating string array in java - java

How would i rotate a string array in java for a tetris game i am making. For example, the string array
[
"JJJJ",
"KKKK",
"UUUU"
]
would become
[
"UKJ",
"UKJ",
"UKJ",
"UKJ"
]
I can do it with a char matrix using this code
public char[][] rotate(char[][] toRotate)
{
char[][] returnChar = new char[toRotate[0].length][toRotate.length];
for(int rows = 0; rows<toRotate.length; rows++)
{
for(int cols = 0; cols<toRotate[0].length; cols++)
{
returnChar[cols][toRotate.length-1-rows]=toRotate[rows][cols];
}
}
return returnChar;
}

With the Array String is similar to want you have done:
public static String[] rotate(String [] toRotate)
{
String [] returnChar = new String[toRotate[0].length()];
String [] result = new String[toRotate[0].length()];
Arrays.fill(returnChar, "");
for(int rows = 0; rows<toRotate.length; rows++)
for(int cols = 0 ; cols < toRotate[rows].length(); cols++)
returnChar[cols] = returnChar[cols] + toRotate[rows].charAt(cols);
for(int i = 0; i < returnChar.length; i++)
result[i] = new StringBuffer(returnChar[i]).reverse().toString();
return result;
}
I go through all char in each String on array toRotate, concat this char (toRotate[rows].charAt(cols)) to each String returnChar[cols] on the array returnChar

Strings are immutable in Java, so you have a few options
Write a wrapper for rotate(char [][]) that turns it back into a string array
Modify the function to create a new array of strings from the input
Create a data structure that holds the data in the most efficient format and then has getters that return it in the format you want it.
3 is essentially what you 'should' be doing. In a Tetris game, you would create a matrix of the size of the game field (possibly padded).

This function does the job of converting the Strings into char[][] so you can use your function.
public static String[] rotateString(String[] toRotate) {
char[][] charStrings = new char[toRotate.length][];
for(int i = 0; i < toRotate.length; i++) {
charStrings[i] = toRotate[i].toCharArray();
}
// This is YOUR rotate function
char[][] rotatedStrings = rotate(charStrings);
String[] returnStrings = new String[rotatedStrings.length];
for(int i = 0; i < rotatedStrings.length; i++) {
returnStrings[i] = new String(rotatedStrings[i]);
}
return returnStrings;
}

Related

Filling a 2d character array from a file in java

I'm a beginner in java and I am trying to fill a 2d character array from an input file. To do this I constructed a method which takes in a 2d character array as a parameter variable, then reads the file and stores it as a character array. So far I have done everything except fill the array, as when I run the code the program throws a NoSuchElement exception. If anyone could help me with this I would greatly appreciate it.
public static char [][] MakeWordArray (char [][] givenArray)
{
try
{
File wordFile= new File ("words.txt");
Scanner in= new Scanner (wordFile);
int rows =0;
int col=0;
while (in.hasNextLine())
{
rows = rows + 1;
col = col + 1;
in.next();
}
char [][] words = new char [rows][col];
File wordFile2= new File ("words.txt");
Scanner in2= new Scanner(wordFile2);
for ( int i = 0; i < rows; i++)
{
for (int j = 0; j < col; j++)
{
String wordly = in2.nextLine();
words [i][j] = wordly.charAt(i);
}
}
return words;
}
catch (FileNotFoundException e)
{
System.out.println("File Does Not Exist");
}
return null;
}
I think your counting methods have some problems.
If you want to count how many lines your .txt have:
int counter = 0;
while (in.hasNextLine())
{
counter++;
in.nextLine();
}
If you want to count how many char your .txt have:
int counterWithoutSpace = 0, counterWithSpace = 0;
while (in.hasNextLine())
{
String line = in.nextLine();
Scanner inLine = new Scanner(line);
while (inLine.hasNext())
{
String nextWord = inLine.next();
counterWithoutSpace += nextWord.length();
counterWithSpace += nextWord.length() + 1;
}
counterWithSpace--;
}
If you want to count how many char you have on each line, I recommend ArrayList. Because the size of your array is dynamic.
Note that you can also you can use the char counter logic above with List too.See as follows:
List<Integer> arr = new ArrayList<Integer>();
while (in.hasNextLine())
{
arr.add(in.nextLine().length());
}
And if you realy needs the static array, you can use:
Integer[] intArr = arr.toArray(new Integer[0]);
You can transform its entire function as below to get a list of every Character of the .txt:
List<Character> arr = new ArrayList<Character>();
while (in.hasNextLine())
{
String line = in.nextLine();
for (char c : line.toCharArray())
{
arr.add(c);
}
}
Try using a do while loop instead of the while
do
{
rows=rows+1;
col=lol+1;
in.next();
}
while(in.hasNext());
There are multiple questions here.
1) Why did you provide a char[][] parameter when you are not even using it?
2) Why are you using two files when all you need to do is read from a file and convert it in 2d Array?
3) The method name should follow camel casing convention.
From what i understood from your question, This is a code i've tried.
NOTE- because the requirement is of an Array and not dynamic datatypes like List ArrayList etc., the data entered into char array might be lost
Saying that here is what works.
public class StackOverflow{
public static char [][] makeWordArray ()
{
try{
File f = new File("C:\\docs\\mytextfile.txt");
Scanner scan = new Scanner(f);
int row = 0, col = 0;
String readData = "";
while(scan.hasNextLine()){
readData += scan.nextLine();
row++;
}
double range = (readData.length()/row);
col = (int)Math.ceil(range);
char[][] arr = new char[row][col];
int count = 0;
for (int i = 0; i < row; i++){
for(int j = 0; j < col; j++){
arr[i][j] = readData.charAt(count++);
System.out.println("Pos: ["+ i +"][" + j + "]" + arr[i][j]);
}
}
return arr;
}
catch(FileNotFoundException fe){
System.err.println(fe.getMessage());
return null;
}
}
public static void main(String[] arg){
char[][] myarr = StackOverflow.makeWordArray();
//print your array
}
}

How to convert a char array to an int array?

Say I am using this code to convert a String (containing numbers) to an array of characters, which I want to convert to an array of numbers (int).
(Then I want to do this for another string of numbers, and add the two int arrays to give another int array of their addition.)
What should I do?
import java.util.Scanner;
public class stringHundredDigitArray {
/**
* #param args
*/
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.print("Enter the number: ");
String num1 = in.nextLine();
char[] num1CharArray = num1.toCharArray();
//for (int i = 0; i < num1CharArray.length; i++){
//System.out.print(" "+num1CharArray[i]);
//}
int[] num1intarray = new int[num1CharArray.length];
for (int i = 0; i < num1CharArray.length; i++){
num1intarray[i] = num1CharArray[i];
}
for (int i = 0; i < num1intarray.length; i++){ //this code prints presumably the ascii values of the number characters, not the numbers themselves. This is the problem.
System.out.print(" "+num1intarray[i]);
}
}
}
I really have to split the string, to preferably an array of additionable data types.
try Character.getNumericValue(char); this:
for (int i = 0; i < num1CharArray.length; i++){
num1intarray[i] = Character.getNumericValue(num1CharArray[i]);
}
Try This :
int[] num1intarray = new int[num1CharArray.length];
for (int i = 0; i < num1CharArray.length; i++)
{
num1intarray[i]=Integer.parseInt(""+num1CharArray[i]);
System.out.print(num1intarray[i]);
}
Short and simple solution!
int[] result = new int[charArray.length];
Arrays.setAll(result, i -> Character.getNumericValue(charArray[i]));

Update 2d String array with method that takes in two 2d string arrays

I have to take in a 2d array and multiple each row of it by the other corresponding 2d array.
Here are the files:
Omaha,104,1218,418,216,438,618,274,234,510,538,740,540
Saint Louis,72,1006,392,686,626,670,204,286,236,344,394,930
Des Moines,116,1226,476,330,444,464,366,230,602,260,518,692
Chicago,408,948,80,472,626,290,372,282,488,456,376,580
Kansas City,308,1210,450,234,616,414,500,330,486,214,638,586
Austin,500,812,226,470,388,488,512,254,210,388,738,686
Houston,454,1086,430,616,356,534,218,420,494,382,476,846
New Orleans,304,1278,352,598,288,228,532,418,314,496,616,882
File Two:
Omaha,7.5
Saint Louis,10.5
Des Moines,8.5
Chicago,11.5
Kansas City,12.5
Austin,10.75
Houston,12.5
New Orleans,9.25
Example: When I compare array[0][0] to price[0][0] the strings match therefore I must take the whole ROW of array[0] and multiply each element by that of price[0][1] to update the array.
Now here is my code:
public static String [][] updateString(String[][] array, String[][] prices)
{
String [][] newArray = new String[array.length][];
for(int row = 0; row < array.length; row++)
{
if (array[row][0].equals(prices[row][0]))
{
for(int i = 0; i<array.length; i++)
{
Double d=Double.parseDouble(array[row][i+1]) * Double.parseDouble(prices[row][1]);
newArray[row][i+1] = d.toString();
}
}
}
return newArray;
}
Here are my errors I'm getting:
Exception in thread "main" java.lang.NullPointerException
at assign_1.DansUtilities.updateString(DansUtilities.java:430)
at assign_1.SalesReportGenerator.main(SalesReportGenerator.java:50)
**line 430 is my method. line 50 is where I call it.
new code:
public static String [][] updateString(String[][] array, String[][] prices)
{
for(int row = 0; row < array.length; row++)
{
if (array[row][0].equals(prices[row][0]))
{
for(int i = 0; i<array[row].length; i++)
{
{Double d=Double.parseDouble(array[row][i]) * Double.parseDouble(prices[row][1]);
array[row][i] = d.toString();}
}
}
}
return array;
heres my new errors:
Exception in thread "main" java.lang.NumberFormatException: For input string: "Omaha"
at sun.misc.FloatingDecimal.readJavaFormatString(Unknown Source)
at java.lang.Double.parseDouble(Unknown Source)
at assign_1.DansUtilities.updateString(DansUtilities.java:429)
at assign_1.SalesReportGenerator.main(SalesReportGenerator.java:50)
NullPointerException can only be thrown if your array is null. Check in the code that is calling the method.
Other notes to improve your code:
you do not need a new array to store values. You can do it in existing array itself.
your inner for loop must be from 1 to the length of current row not the length of the array so it should be something like:
for(int i=1;i<array[row].length;i++)
And use index i instead of i+1 in loop content.
I suggest to create output of your strings, to see whether they are correctly read from files.
private static void outputString2D(String[][] s, String name) {
for ( int i = 0; i < s.length; i++) {
for ( int j = 0; j < s[i].length; j++ ) {
System.out.println(name + " contains at [" + i + "][" + j + "]:\t" + s[i][j]);
}
}
}
Example how I used it:
public static void main(String[] args) {
String[][] str = new String[2][3];
str[0][0] = new String("I am 0,0.");
str[0][1] = new String("I am 0,1.");
str[0][2] = new String("I am 0,2.");
str[1][0] = new String("I am 1,0.");
str[1][1] = new String("I am 1,1.");
str[1][2] = new String("I am 1,2.");
outputString2D(str, "str");
}
Example output:
str contains at [0][0]: I am 0,0.
str contains at [0][1]: I am 0,1.
str contains at [0][2]: I am 0,2.
str contains at [1][0]: I am 1,0.
str contains at [1][1]: I am 1,1.
str contains at [1][2]: I am 1,2.
Provide us the content of your two strings please.

Set Method And Get Method Of A Fixed Size Array

I'm a bit mixed up on how to apply the 'sets' and 'gets' methods for a fixed array. Here is some of my work in Netbeans:
//creating 5 fixed arrays of size 10
private String [] itemnames = new String [10];
private String [] itemcodes = new String [10];
private String [] category = new String [10];
private String [] quantity = new String [10];
private Double [] sellingprice = new Double [10];
//initialising each array to null in the class constructor
for (int i = 0; i < 10; i++){
itemnames[i] = "";
}
for (int i = 0; i < 10; i++){
itemcodes[i] = "";
}
for (int i = 0; i < 10; i++){
category[i] = "";
}
for (int i = 0; i < 10; i++){
quantity[i] = "";
}
for (int i = 0; i < 10; i++){
(Double.parseDouble(sellingprice[i])) = 0;
}
Now, i'm stuck in the set method and the get method of each array. Any help please?
Thanks :)
You make set and get methods according to what you want to do (or later be able to do) with the arrays.
If you want to be able to retrieve an array into another class, you could make a get method like this:
public String[] getItems()
{
return itemnames;
}
If on the other hand you only want other classes to get the specific items in your arrays, one method might look like this:
public String getItemMatchingCode(String code)
{
for(int i = 0; i < ARR_LENGTH; i++)
{
if(code.equals(itemcodes[i]) return itemnames[i];
}
}
Or you might want to set and get the different values based on ideces:
public String getItemnameAt(int i)
{
return itemnames[i];
}
public void setItemnameAt(int i, String newItemname)
{
itemnames[i] = newItemname;
}
Sidenotes:
You are not "//initialising each array to null in the class constructor", they are that by default. What you are doing is filling them with empty strings, which in most cases is unnecessary.
When iterating through the arrays and filling them with values you can do them all in one loop.
for (int i = 0; i < 10; i++)
{
itemnames[i] = "";
itemcodes[i] = "";
category[i] = "";
}
Edit:
Also consider using a constant when declaring the size of the arrays, like so:
private static final int ARR_SIZE = 10;
private String[] array = new String[ARR_SIZE];

List<String> ----> to int [ ] [ ] arr

Well I have been stumped as to the best way to do this, I have written the code to read in lines of code from txt files as List. I can then print specific parts or convert this to an array of objects. But, ultimately I would like to have just a 2d int array you can see often in C/C++. I am very green when it comes to java, having only started earlier this week. I have like it up until this point of making dynamic 2d arrays at run time. Can any of you suggest a good way to get to a 2d int array from where i am currently stuck. I was just about to convert it to a char array using 'toChar', then to take the (value#index-48) and store it in its corresponding spot, but that seems pretty ghetto to me.
====updated==========================
eh, thanks for all the replies, but I just figured out how to do it using doubles, so for anyone else, here you go. I would still rather have int, since I have already built my other matrixops classes using this type, but Double shouldn't be an issue i guess.
package uaa.cse215;
import java.io.*;
import java.util.*;
public class ReadMatrix {
private Double[][] A;
private Double[][] B;
private int count;
public int filedir(String matrix) throws Exception{
Double[][] Temp;
String[] arr;
BufferedReader rd = new BufferedReader(new FileReader(matrix));
String s;
List<String> textFile = new ArrayList<String>();
while ((s=rd.readLine())!=null) {
textFile.add(s);
}
String splitarray[] = textFile.get(0).split(" ");//run once to grab # cols
int rows = textFile.size();//number of rows
int cols = splitarray.length;//number of cols
Temp = new Double[rows][cols]; // now can initiate array
for (int i=0; i<rows; i++) {
s = textFile.get(i);
arr = s.split(" ");
for (int j=0; j<cols; j++) {
Temp[i][j] = Double.parseDouble(arr[j]);
}
}
count++;
if (count == 1){
A = Temp;
}
else
B = Temp;
rd.close();
return(1);
}
}
Please note that Java has the char data type which is a 16bit unsigned integer holding a UTF-16 code point. int is in Java always a signed 32 bit integer. So if you want a C like Arrays of chars representing the content of a String, you should use a char[][]
To convert the content of your List<String> into a 2d array you can use the following code:
char[][] twoDarray = new char[textFile.size()];
for(int i = 0; i < textFile.size(); i+)
{
twoDarray[i] = textFile.get(i).toCharArray();
}
The array twoDarray then contains all Strings each as a char array.
This line won't compile
splitarray[j] = textFile.get(i).split(" ");
as splitarray[j] is of type String and split returns an array of Strings
Do the following instead:
for(int row=0;row<textFile.size();row++){
String[] splitarray = textFile.get(row).split(" ");
for(int col=0;col<splitarray.length;col++){
tmp[row][col] = Integer.parse(splitarray[col]);
}
}
if the input matrix dimentions are dynamic or jagged you can use
List<ArrayList<Integer>> list = new ArrayList<ArrayList<Integer>>();
to read numbers and than copy it to raw 2d array if you want.
java.util.Scanner has many handy methods for reading "typed" data from input
Here's an example reading file to 2D array
public static int[][] read2DArray(String fileName) throws FileNotFoundException {
Scanner sc = null;
List<ArrayList<Integer>> list = new ArrayList<ArrayList<Integer>>();
int columnCount = 0;
int[][] arr = null;
try {
sc = new Scanner(new File(fileName));
while (sc.hasNextLine()) {
// Read line
String line = sc.nextLine();
// Split it
String[] nums = line.split(" ");
if (nums.length > columnCount) {
columnCount = nums.length;
}
// Convert to integers and add to list
list.add(new ArrayList<Integer>());
for (String n : nums) {
list.get(list.size() - 1).add(new Integer(n));
}
}
// Convert list to array
int rowCount = list.size();
arr = new int[rowCount][columnCount];
for (int i = 0; i < rowCount; i++) {
for (int j = 0; j < list.get(i).size(); j++) {
arr[i][j] = list.get(i).get(j);
}
}
} finally {
if (sc != null) {
sc.close();
}
}
return arr;
}
Assuming your data file contains ascii-represented numbers that you want parsed into integers:
11 -9 13
12 55 102
1 1 1024
Then you can use the Integer(String s) constructor to parse your string objects.
Also, I suggest splitting each row only once. It won't matter much for small arrays, but the larger your inputs get, the more you'll needlessly recompute the splits.
An (untested) re-writing:
int tmp[][] = new int [rows][cols];
for(int i=0;i<rows;i++){
splitarray = textFile.get(i).split(" ");
for(int j=0;j<cols;j++){
tmp[i][j] = Integer(splitarray[j]);
}
}

Categories

Resources