Storing in an array - java

I'm trying to get a string to read a file, that then stores all the digits in an array that can be recalled one by one in another loop. Name the array digitStorage please :D Here's my current bit of code:
for (int i = 0; i <= 40000 ; i++) {
String digit;
if ( i <=39998)
digit = pictureFile.substring(i, i+1);
else
digit = pictureFile.substring(39998,39999);
My question :
What to do, how could I do this, how would I get it to read each digit (single integers) 1 by 1 and then store them 1 by 1 in an array that could be later recalled, each number corresponds to a color that would be used to sketch a picture in a graphics window (there are 40,000 single digit integers in a file that i've already worked out how to read) ?
Cheers.

As you have mentioned that you have already read the file and you want to store it in some kind of array. Below code will work.
List<String> list = new ArrayList<String>();
for (int i = 0; i <= 40000 ; i++) {
String digit;
if ( i <=39998)
list.add(pictureFile.substring(i, i+1));
else
list.add(pictureFile.substring(39998,39999));
}
If you want List of Integer then us.
List<Integer> list = new ArrayList<Integer>();
for (int i = 0; i <= 40000 ; i++) {
String digit;
if ( i <=39998)
list.add(Integer.parseInt(pictureFile.substring(i, i+1)));
else
list.add(Integer.parseInt(pictureFile.substring(39998,39999)));
}
You can iterate through list after this.

Your question is not very clear, but I believe this should do it:
int [] digitStorage = new int[40000];
for (int i = 0; i <= 40000 ; i++) {
if ( i <=39998)
int[i] = Integer.parseInt(pictureFile.substring(i, i+1));
else
int[i] = Integer.parseInt(pictureFile.substring(39998,39999));

Based on your comments and question, the easiest solution I can think of is to use String.toCharArray() and Character.digit(char, int) like
char[] chars = pictureFile.toCharArray();
int[] digitStorage = new int[chars.length];
for (int i = 0; i < chars.length; i++) {
digitStorage[i] = Character.digit(chars[i], 10);
}
System.out.println(Arrays.toString(digitStorage));

Related

Winkler's table in Java

I'm making a chat-bot, which will answer you by nearest value in dataset (treemaps). System is analog of AIML.
I need to make Winkler-table, which will give me array of result numbers. How to do that?
There is an image, which show how this table works:
You can do it in 3 easy steps.
Create a 2 dimensional array for the result matrix:
see question Syntax for creating a two-dimensional array.
Dimensions will have to match the input and key lengths of course. See https://docs.oracle.com/javase/10/docs/api/java/lang/String.html#length().
Loop over the characters of the input string, and the key as a nested loop. See https://docs.oracle.com/javase/specs/jls/se7/html/jls-14.html#jls-14.14.1 and https://docs.oracle.com/javase/10/docs/api/java/lang/String.html#charAt(int). Basically you have 2 indices which give you 2 char values.
Compare both characters using the == operator and store 0 or 1 in the two-dimensional array using the indices.
Okey, i made that table.
It looks like next:
String[] ts = new String[s2.length()];
int[][] table = new int[s1.length()][s2.length()];
char[] s1c = s1.toCharArray();
char[] s2c = s2.toCharArray();
for(int s1cl = 0; s1cl <= s1c.length - 1; s1cl++) {
for(int s2cl = 0; s2cl <= s2c.length - 1; s2cl++) {
if(s1c[s1cl] == s2c[s2cl]) {
table[s1cl][s2cl] = 0;
} else {
table[s1cl][s2cl] = 1;
}
}
}
for(int ts1 = 0; ts1 <= s1c.length - 1; ts1++) {
String res = "";
for(int ts2 = 0; ts2 <= s2c.length - 1; ts2++) {
res += ts2;
if(ts2 == s2c.length - 1) {
ts[ts1] = res;
res = "";
}
}
}
Thanks "herman" for your answer!

How to rotate 2-D Array in Java

[SOLVED]
The title of this question is vague but hopefully this will clear things up.
Basically, what I am looking for is a solution to rotating this set of data. This data is set up in a specific way.
Here is an example of how the input and output would look like:
Input:
3
987
654
321
Output:
123
456
789
The '3' represents the number of columns and rows that will be used. If you input the number '4', you will be allowed to input 4 sets of 4 integers.
Input:
4
4567
3456
2345
1234
Output:
1234
2345
3456
4567
The goal is to find a way to rotate the data only if needed. You have to make sure the smallest corner number is at the top left. For example, for the code above, you rotated it so 1 is at the top left.
The problem I have is that I don't know how to rotate the data. I am only able to rotate the corners but not the sides. This is what my code does so far:
take the input of each line and turn them into strings
split those strings into separate characters
store those characters in an array
I just do not know how to compare those characters and in the end rotate the data.
Any help would be appreciated! Any questions will be answered.
A detailed description of the problem is here(problem J4).
This is just a challenge I assigned myself for practice for next year's contest, so giving me the answer won't "spoil" the question, but actually help me learn.
Here is my code so far:
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner kb = new Scanner(System.in);
int max = kb.nextInt();
int maxSqrt = (max * max);
int num[] = new int[max];
String num_string[] = new String[max];
char num_char[] = new char[maxSqrt];
int counter = 0;
int counter_char = 0;
for (counter = 0; counter < max; counter++) {
num[counter] = kb.nextInt();
}
for (counter = 0; counter < max; counter++) {
num_string[counter] = Integer.toString(num[counter]);
}
int varPos = 0, rowPos = 0, charPos = 0, i = 0;
for (counter = 0; counter < maxSqrt; counter++) {
num_char[varPos] = num_string[rowPos].charAt(charPos);
i++;
if (i == max) {
rowPos++;
i = 0;
}
varPos++;
if (charPos == (max - 1)) {
charPos = 0;
} else {
charPos++;
}
}
//
for(int a = 0 ; a < max ; a++){
for(int b = 0 ; b < max ; b++)
{
num_char[counter_char] = num_string[a].charAt(b);
counter_char++;
}
}
//here is where the code should rotate the data
}
}
This is a standard 90 degree clockwise rotation for a 2D array.
I have provided the solution below, but first a few comments.
You said that you're doing this:
take the input of each line and turn them into strings
split those strings into separate characters
store those characters in an array
Firstly youre essentially turning a int matrix into a character matrix. I do not think you need to do this, since even if you do want to compare values, you can use the ints provided.
Secondly, there is no need to compare any 2 data elements in the matrix, since the rotation does not depend on any value.
Here is an adapted solution for java, originally written in C# by Nick Berardi on this question
private int[][] rotateClockWise(int[][] matrix) {
int size = matrix.length;
int[][] ret = new int[size][size];
for (int i = 0; i < size; ++i)
for (int j = 0; j < size; ++j)
ret[i][j] = matrix[size - j - 1][i]; //***
return ret;
}
If you wanted to do a counterCW rotation, replace the starred line with
ret[i][j] = matrix[j][size - i - 1]

How would I add array index's together?

I've read data from a text file and stored them in an array called 'boat1'.
There are nine values and I am trying to add together index's [4] to [9] to get a total value.
How would I go about doing this?
Here is my code:
String[] boat1 = new String[9];
int i = 0;
while(reader.hasNextLine() && i < boat1.length) {
boat1[i] = reader.nextLine();
i++;
}
I've tried to change the values to an integer but it doesn't seem to be working..?
Thank you.
You got to parse before adding:
int a = Integer.parseInt(boat1[3]);
int b = Integer.parseInt(boat1[8]);
int c = a + b;
Your array boat1 is a String array and not an int array. You need to convert it. Note that boat1 is size of 9 meaning that it has indexes from 0 to 8. Java is 0 based.
If you want to add up a sequence of numbers (ex. 3,4,...,7,8), just loop through the indexes you want to add up and keep track of a total.
Because your array is an String type it needs to be converted to int, After you do that you will have something like this example assuming that I'm making up those values , but it should still work for your code :). Don't forget to add the for loop at the end as I have it on my code so it can find the sum of your indexes. Hope it can help you!
int sum = 0;
int[] boat = new int[9];
boat[0] = 2;
boat[1] = 4;
boat[2] = 6;
boat[3] = 8;
boat[4] = 10;
boat[5] = 12;
boat[6] = 14;
boat[7] = 16;
boat[8] = 18;
for(int i = 3; i < boat.length ; i++){
sum += boat[i];
}
System.out.println(sum);

Predicament with arrays and expansion

So I know that the java convention is to use ArrayList<> when it comes to expansions and many other applications. The typical array cannot expand. My java course is elementary so we are still reviewing over arrays right now. As much as I want to use an arraylist I cant. How do I make it to where I store only elements that satisfy the condition in my counter array?
public int[] above100Degrees()
{
int[] blazing = new int[temps.length];
for( int i = 0; i < temps.length; i++ )
{
if( temps[i] > 100 )
{
blazing[i] = temps[i];
}
}
return blazing;
}
Output
The temperature above 100 degrees is: 0 0 0 0 0 0 0 103 108 109
Just count how many elements match your filter first, then create the array, then populate it. It means you'll need to go through the array twice, but there are no really nice alternatives unless you want to end up creating multiple arrays. So something like:
public int[] above100Degrees() {
// First work out how many items match your filter
int count = 0;
// Are you allowed to use the enhanced for loop? It's not necessary, but it
// makes things simpler.
for (int temp : temps) {
if (temp > 100) {
count++;
}
}
// Create an array of the right size...
int[] ret = new int[count];
// ... and populate it.
int index = 0;
for (int temp : temps) {
if (temp > 100) {
ret[index++] = temp;
}
}
return ret;
}
I would use a loop to find how many are above 100 before assigning the array.
public int[] above100Degrees()
{
int newArrayLength=0;
for( int i = 0; i < temps.length; i++ )
{
if( temps[i] > 100 )
{
newArrayLength++;
}
}
int[] blazing = new int[newArrayLength];
int positionInNewArray = 0;
for( int i = 0; i < temps.length; i++ )
{
if( temps[i] > 100 )
{
blazing[positionInNewArray] = temps[i];
positionInNewArray++;
}
}
return blazing;
}
You could do a ternary operation
resultString = "The temperature above 100 degrees is: ";
for(int i = 0; i < blazing.length; i++){
resultString += blazing[i] != 0 ? blazing[i] : "";
}
Note: This would require more memory than JonSkeets answer, but could potentially be more efficient. If your expect your array length to get very large, go with JonSkeet's answer. In other words, this won't scale well.
One way is to count things before setting up the array. Another way is to set up the array first and keep track of the count, then create a new array:
public int[] above100Degrees()
{
int[] blazing = new int[temps.length];
int count = 0;
for( int i = 0; i < temps.length; i++ )
{
if( temps[i] > 100 )
{
blazing[count++] = temps[i];
}
}
// At this point, `count` is the number of elements you're going to return;
// and the first `count` elements of `blazing` hold those elements, while the
// remaining elements of `blazing` are garbage
int[] result = new int[count];
for ( int i = 0; i < count; i++ )
result[i] = blazing[i];
return result;
}
This approach would be better if the condition you're testing for takes a lot of time to calculate (as opposed to temps[i] > 100, which hardly takes any time). You could use Arrays.copy to create the result array, but if you can't use ArrayList you probably can't use Arrays.copy either.
Your code is keeping the cells in blazing array for i <= 100; You need to ignore these and start populating from i = 101.

Adding elements to last array position

Im trying to add an element to an array at its last position in Java, but I am not able to...
Or rather, I don't know how to. This is the code at the moment:
String[] values = split(line, ",");
int[][] coordinates = new int[2][values/2];
for(int i = 0; i < values.length; i++) {
if(i % 2 == 0) { //THIS IS EVEN VALUES AND 0
coordinates[0][coordinates[0].length] = values[i];
} else { //THIS IS ODD VALUE
coordinates[1][coordinates[1].length] = values[i];
}
}
EDITED VERSION:
String[] values = split(line, ",");
int[][] coordinates = new int[2][values/2];
int x_pos = 0;
int y_post = 0;
for(int i = 0; i < values.length; i++) {
if(i % 2 == 0) { //THIS IS EVEN VALUES AND 0
coordinates[0][x_pos] = values[i];
x_pos++;
} else { //THIS IS ODD VALUE
coordinates[1][y_pos] = values[i];
y_pos++;
}
}
values is being read from a CSV file. My code is I believe wrong, since it will try to add the values always at the maximum array size for coordinates[] in both cases.
How would I go around adding them at the last set position?
Thanks!
/e: Would the EDITED VERSION be correct?
Your original code has two problems:
it addresses the array badly, the las element in a Java array is at position length-1, and this would result in an ArrayOutOfBoundsException
even if you'd correct it by subtracting 1, you would always overwrite the last element only, as the length of a Java array is not related to how many elements it contains, but how many elements it was initialised to contain.
Instead of:
coordinates[0][coordinates[0].length] = values[i];
You could use:
coordinates[0][(int)Math.round(i/2.0)] = values[i];
(and of course, same with coordinates[1]...)
EDIT
This is ugly of course:
(int)Math.round(i/2.0)
but the solution I'd use is far less easy to understand:
i>>1
This is a right shift operator, exactly the kind of thing needed here, and is quicker than every other approach...
Conclusion: this is to be used in a live scenario:
Use
coordinates[0][i>>1] = values[i];
EDIT2
One learns new things every day...
This is just as good, maybe a bit slower.
coordinates[0][i/2] = values[i];
If you know you'll definitely have an even number of values you can do
for(int i = 0; i < values.length / 2; i++) {
coordinates[0][i] = values[2*i];
coordinates[1][i] = values[2*i + 1];
}
You have to store the last position somewhere. .length gives you the size of the array.
The position in the array will always be the half of i (since you put half of the elements in one array and the other half in the other).
String[] values = split(line, ",");
int[][] coordinates = new int[2][values/2];
for(int i = 0; i < values.length; i++) {
if(i % 2 == 0) { //THIS IS EVEN VALUES AND 0
coordinates[0][ i / 2] = values[i];
} else { //THIS IS ODD VALUE
coordinates[1][ i / 2 + 1 ] = values[i];
}
}
The array index for java is from "0" to "array length - 1".
http://docs.oracle.com/javase/tutorial/java/nutsandbolts/arrays.html
Each item in an array is called an element, and each element is accessed by its numerical index. As shown in the above illustration, numbering begins with 0. The 9th element, for example, would therefore be accessed at index 8.
why not:
String[] values = split(line, ",");
int[][] coordinates = new int[2][values/2];
for(int i = 0; i < values.length; i+=2) {
coordinates[0][i/2] = values[i];
coordinates[1][i/2] = values[i+1];
}

Categories

Resources