I'm running into a problem whenever I try to take the data from a file and make an array and an int out of that data.
For this specific problem, we're given 17 data points in this style:
13 24 35 46 57 68 79 80 32 43 54 65 76 87 98 27
438
What I'm trying to do is make an array from the first row, and make the second row's single variable into an int.
How would I do this in java?
(for the problem, the second variable is what we check our results against, so I do want it as an int or atleast in it's own array)
You can use this :
String line = "13 24 35 46 57 68 79 80 32 43 54 65 76 87 98 27";
String[] array = line.split(" ");
If you want to use this numbers for counting, you need to change them to integer.
int[] intarray = new int[array.length];
for (int i = 0; i < array.length; i++) {
intarray[i] = Integer.valueOf(array[i]);
}
Related
I have a text file which is tab delimited, but there are a different number of columns on each line. Here is an example:
1 : 2 16 17 24 31 34 40 41 45 47 48
2 : 1 3 4 5 6 7 8 13 18 20 22 28 33 35 37 38 42 44 46 49
3 : 2 10 12 16 17 19 24 25 29 31 34 40 41 45
I want to use the split function, like I did here for a different assignment:
String[] words = line.split("\t");
col1 = Integer.parseInt(words[0]);
col2 = Integer.parseInt(words[1]);
col3 = Integer.parseInt(words[2]);
col4 = Integer.parseInt(words[3]);
This puts each column from a line into a different variable. I want to do the same but I'm not sure how to do this with a varying number of columns.
As said in the comments, you're quite good with what you've done. If you really want to have your Integer values stored somehow, you could simply use an Integer array, and fill it with a loop like this:
String[] words = line.split("\t");
int[] numbers = new int[words.length];
for (int i = 0; i < words.length; i++)
{
numbers[i] = Integer.parseInt(words[i]);
}
That whole thing being inside the loop you use to iterate your lines.
I don't think you need anything more complex than an array.
I have a 2D array with 3 columns. When it prints, I need it to tab. I am using the /t and /n for next line but it is displaying in a straight line across instead of staying in rows. I will put my code in. How do I fix it?
package presidnetssort;
import java.io.*;
import java.util.*;
``import edu.princeton.cs.introcs.*;
public class PresidentsSort
{
public static void main(String[] args) throws FileNotFoundException
{
//Create scanner object to read the file.
Scanner x = new Scanner(new File("PresidentsGrades.txt"));
//Create a string array to hold the data from the file.
String[][] a = new String[44][3];
//Create a loop to to add the file data to the array.
for (int i=0;i<a.length;i++)
{
a[i][0]=x.next();
a[i][1]=x.next();
a[i][2]=x.next();
}
//Call the sorting methods. I am commenting them out. Uncomment them one at a time to use them.
//sortNames(a);
//sortCourses(a);
//sortGrades(a);
//Call the print method to print the a array.
print(a);
StdOut.printf("/t,/t/n",a);
}
public static void sortNames(String[][] a)
{
Arrays.toString(a);
StdOut.printf("/t",a);
}
public static void sortCourses(String[][] a)
{
Arrays.toString(a);
print(a);
}
public static void sortGrades(String[][] a)
{
Arrays.toString(a);
print(a);
}
static void print(String[][] a)
{
for (int i=0;i<a.length;i++)
{
for (int j=0;j<a[0].length;j++)
System.out.print(a[i][j]+" ");
StdOut.printf("/t,/t/n",a);
}
}
}
my output displays as:
Wasington Algorithm 98 /t,/t/nAdams Math 89 /t,/t/nJefferson Java 85 /t,/t/nMadison C# 83 /t,/t/nMonroe Web 88 /t,/t/nAdams Algorithm 81 /t,/t/n
When I take the formatting out and do not use StdOut.print, it prints in rows as it should but not tabbed, like this:
Wasington Algorithm 98
Adams Math 89
Jefferson Java 85
Madison C# 83
Monroe Web 88
Adams Algorithm 81
Jackson Java 78
Buren C# 75
Harrison Computers 45
Tyler Algorithm 73
Polk Java 68
Taylor Algorithm 88
Fillmore Web 93
Pierce Math 56
Buchanan Algorithm 77
Lincoln Algorithm 99
Johnson C# 76
Grant Algorithm 92
Hayes Web 76
Garfield Computers 66
Arthur Web 77
Cleveland Java 88
Harrison Algorithm 75
Cleveland C# 91
McKinley Algorithm 100
Roosevelt Web 79
Taft C# 86
Wilson C# 84
Harding Web 67
Coolidge Math 67
Hoover History 76
Roosevelt History 84
Truman Math 83
Eisenhower History 100
Kennedy Java 95
Johnson Algorithm 56
Nixon History 23
Ford History 78
Carter Math 55
Regan Algorithm 99
Bush Algorithm 89
Clinton History 45
Bush Math 75
Obama History 13
The tab and new line characters are \t and \n respectively, change
StdOut.printf("/t,/t/n",a);
to something like
StdOut.printf("\t,\t\n",a);
and
StdOut.printf("/t",a);
to
StdOut.printf("\t",a);
and so on...
Deletion(int array[ ], int delete, int position)
So I have this method, see above, the first parameter is the name of the array, the second is the value I want deleted, and the third is the index of which it can be found. For example:
Deletion(list,50,4);
In this case, the array I chose is called list, the value I want deleted is 50, and the index of which the value is located is 4.
If we were to use Deletion(list,50,4), this method is supposed to replace the 50 at the index of 4 with the element at the index of 5 and the element at index of 5 is replaced with the element at index of 6 and so on.
If this is the array list: 90 76 55 48 50 69 66 52 87 56 89 91 86 73 50 68 52 75 54 45
The output should be: 90 76 55 48 69 66 52 87 56 89 91 86 73 50 68 52 75 54 45 45
However,I can only get it to replace the 50 but not any of the other numbers.
This is the output I get: 90 76 55 48 69 69 66 52 87 56 89 91 86 73 50 68 52 75 54 45
The 50 is replaced with the 69 but everything else stays the same, I need the other elements to "shift" to the left.
Here is my code so far for the Deletion method:
for (int i=array.length-1; i<position; i ++)
array[i] = array[ i+1];
array[position] = array[position+1]
The length of the list is 20, subtract 1, so i = 19. I know 19 is not less than 4 so it skips the for loop, but if I made it i > position, I get this error:
java.lang.ArrayIndexOutOfBoundsException: 20
So this is where I'm stuck. Please help!
You need to redefine the value of i so that it is initialized as the the int value of position (so that your deletion/replacement process can start there).
for (int i = position; i < array.length - 2; i++)
{
array[i] = array[i+1];
}
Your i.max_value should be array.length-2 so that i will incrementally increase until the end of the array. It shouldn't be -1 since you are essentially deleting the last index of your array (as the value has nothing)
You'd better be using System.arraycopy instead on implementing your own algorithm for moving array elements. Like this:
System.arraycopy(array, position+1, array, position, array.length-position);
Also see this question: Delete item from array and shrink array
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
In order to prevent duplicates in my random number generator, I want to make an if statement that tests if my random number (x) is the same as any other previous values of x. If it is, then it returns and restarts the loop.
How do I have my code remember all of the previous values of x?
Pseudocode:
if (x == previous value of x) {
return;
}
Explanation: For example, you can make a list that contains 8 numbers and after that shuffle the list in order to be randomized what you want.
Code:
Integer[] array = new Integer[100];
for (int i = 0; i < 100; i++) {
array[i] = i+1;
}
List<Integer> list = Arrays.asList(array);
Collections.shuffle(list);
for (int i = 0; i < list.size(); i++) {
System.out.print(list.get(i) + " ");
}
Output:
88 25 24 15 92 87 14 100 68 98 91 32 28 22 74 37 10 90 44 77 94 52 34
86 72 99 46 71 36 26 69 55 82 79 19 78 60 49 70 85 33 66 45 57 61 9 51
76 3 42 16 29 84 93 58 2 53 97 6 17 13 43 12 56 35 96 83 40 38 59 50 5
41 65 11 23 73 4 47 89 1 81 21 80 63 48 20 27 64 54 18 75 30 62 39 31
7 8 67 9
Use a list to record the previous values of x. List are better than arrays for this purpose, because you don't need to resize them if you want to generate more random numbers.
List<int> randomNumberList = new ArrayList<int>();
randomNumberList.add(randomNumberThatYouGenerated);
then just use an if:
if (randomNumberList.contains(randomNumberThatYouGenerated)) {
//code
}
Use a array to record the previous value of x..... and check if the currently value inside that array..
This question is unlikely to help any future visitors; it is only relevant to a small geographic area, a specific moment in time, or an extraordinarily narrow situation that is not generally applicable to the worldwide audience of the internet. For help making this question more broadly applicable, visit the help center.
Closed 11 years ago.
I'm currently trying to solve problem 18 of project Euler. The goal is:
By starting at the top of the triangle below and moving to adjacent numbers on the row below, the maximum total from top to bottom is 23.
3
7 4
2 4 6
8 5 9 3
That is, 3 + 7 + 4 + 9 = 23.
Find the maximum total from top to bottom of the triangle below:
75
95 64
17 47 82
18 35 87 10
20 04 82 47 65
19 01 23 75 03 34
88 02 77 73 07 63 67
99 65 04 28 06 16 70 92
41 41 26 56 83 40 80 70 33
41 48 72 33 47 32 37 16 94 29
53 71 44 65 25 43 91 52 97 51 14
70 11 33 28 77 73 17 78 39 68 17 57
91 71 52 38 17 14 91 43 58 50 27 29 48
63 66 04 68 89 53 67 30 73 16 69 87 40 31
04 62 98 27 23 09 70 98 73 93 38 53 60 04 23
I tried to solve it with the following algorithm:
public static void main(String[] args) throws NumberFormatException, IOException {
int[][] values = readFile();
int depth = values.length - 2;
while ( depth >= 0) {
for (int j = 0; j < depth; j++) {
values[depth][j] += Math.max( values[depth+1][j], values[depth+1][j+1]);
}
depth += -1;
}
values[0][0] += Math.max(values[1][0], values[1][1]);
System.out.println("The maximum path sum is: " + values[0][0]);
}
The array values contains all the numbers from the triangle where values[0][0] is the element in the top row and values[n][n] is the last element in the last row.
The algorithm uses the approach that if for example I start in the last row and have the choice between 04 + 63 and 62 + 63, the sum of the field in which 63 was will be set to 125 because this is the highest amount. This algorithm works for the small triangle, but for the big triangle it seems to fail. I'm not sure why and would appreciate every hint.
I believe that the line:
for (int j = 0; j < depth; j++) {
should be
for (int j = 0; j <= depth; j++) {
because right now you aren't visiting the last element on each row. Of course, then you don't need the line
values[0][0] += Math.max(values[1][0], values[1][1]);
because it is already done in the loop.
I don't know the correct algorithm, but there's an easy proof of #Johns comment on the question, that the best local choice doesn't necessarily lead to the best global solution.
Consider this (extreme) example:
1
1 0
1 0 1000
1 0 0 0
1 0 0 0 0
Given your algorithm, you'd obviously go down the very left of the path and never read the 1000 that must be on the best path.
This may not be the best solution, but what if for each iteration you kept track of the sum to that point. Then when you go to the last row the max value would be your answer.