I have two files formatted as follows below where the first int needs to be stored somewhere and the second line and down are going to be stored into a 2d array. The first number, in this case, 4, will indicate the size as int [][] array = new int [2*4][4]; The 4, however, should not be part of the array and should be discarded. The file paths will be provided to the program via the command line. I haven't been able to find any could that could perform this function.
4
7 5 6 4
5 4 6 7
4 5 6 7
4 5 6 7
I have used java 7 API to read file into a list.
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.List;
public class SOTest {
public static void main(String[] args) throws IOException {
int[][] arr = null;
String path = args[0];
List<String> lines = Files.readAllLines(Paths.get(path));
for (int i=0; i<lines.size() ; i++) {
String[] aStr = lines.get(i).split("\\s+");
if(aStr.length==1) {
int size = Integer.valueOf(aStr[0]);
System.out.println("Size of array "+size);
arr = new int[size][size];
populateArr(arr, lines.subList(i+1, i+size+1));
print(arr);
i = i+size;
}
}
}
public static void populateArr(int[][] arr, List<String> list) {
for(int i=0; i<list.size(); i++) {
String[] values = list.get(i).split("\\s+");
for(int j=0; j<values.length; j++) {
arr[i][j] = Integer.parseInt(values[j]);
}
}
}
private static void print(int[][] arr) {
System.out.println("***********PRINT***********");
for(int i=0; i<arr.length; i++) {
for(int j=0; j<arr[i].length; j++) {
System.out.print(arr[i][j]+" ");
}
System.out.println();
}
}
}
Input (File location)
file content is as below
4
7 5 6 4
5 4 6 7
4 5 6 7
4 5 6 7
3
1 2 3
4 5 6
7 8 9
output from java program
Size of array 4
***********PRINT***********
7 5 6 4
5 4 6 7
4 5 6 7
4 5 6 7
Size of array 3
***********PRINT***********
1 2 3
4 5 6
7 8 9
Related
I'm trying to write an insertion sort, and I pass several test cases, but I fail one. My code is:
static void insertionSort1(int n, int[] arr) {
int copy = arr[n-1];
int i = n - 1;
while (copy < arr[i-1]){
arr[i] = arr[i-1];
for(int k = 0; k < arr.length; k++){
System.out.print(arr[k] + " ");
}
System.out.println();
i--;
}
arr[i] = copy;
for(int m = 0; m < arr.length; m++){
System.out.print(arr[m] + " ");
}
}
where n is the size of the array, and arr is the array. My algo fails this test case in particular:
10
2 3 4 5 6 7 8 9 10 1
I get index out of bounds on that but not on
5
2 4 6 8 3
or others. what's going on?
That is an index out of bound exception of the array because of minus value of the arr. It is not an algorithm issue but a language.
while (i > 0 && copy < arr[i - 1])
Source:
public class InsertionSort {
static void insertionSort1(int n, int[] arr) {
int copy = arr[n - 1];
int i = n - 1;
while (i > 0 && copy < arr[i - 1]) {
arr[i] = arr[i - 1];
for (int k = 0; k < arr.length; k++) {
System.out.print(arr[k] + " ");
}
System.out.println();
i--;
}
arr[i] = copy;
System.out.println("#### RESULT ####");
for (int m = 0; m < arr.length; m++) {
System.out.print(arr[m] + " ");
}
System.out.println("\n#### END ####\n");
}
public static void main(String[] args)
{
//10
//2 3 4 5 6 7 8 9 10 1
int[] arr ={2, 3, 4, 5, 6, 7, 8, 9, 10, 1};
int n = arr.length;
insertionSort1(n, arr);
//5
//2 4 6 8 3
arr= new int[5];
n = arr.length;
arr[0] = 2;
arr[1] = 4;
arr[2] = 6;
arr[3] = 8;
arr[4] = 3;
insertionSort1(n, arr);
}
}
Result:
2 3 4 5 6 7 8 9 10 10
2 3 4 5 6 7 8 9 9 10
2 3 4 5 6 7 8 8 9 10
2 3 4 5 6 7 7 8 9 10
2 3 4 5 6 6 7 8 9 10
2 3 4 5 5 6 7 8 9 10
2 3 4 4 5 6 7 8 9 10
2 3 3 4 5 6 7 8 9 10
2 2 3 4 5 6 7 8 9 10
#### RESULT ####
1 2 3 4 5 6 7 8 9 10
#### END ####
2 4 6 8 8
2 4 6 6 8
2 4 4 6 8
#### RESULT ####
2 3 4 6 8
#### END ####
Have a good day.
First, you should review what an insertion sort is. You should be building a sorted list on one end of the array, expanding it one element at a time by "inserting" the next value in the correct place. It should be much like sorting a hand of cards if you are given them one at a time. You will need a nested loop to do it correctly.
Carefully consider what your program is really doing and see why it fails -- a shorter test case that fails in the same way would be [3, 2, 1]. Or [2, 1], for that matter.
can someone please check my code as to why the last index is not working as intended? Any advice on how to improve this is much appreciated.
import java.io.*;
import java.util.*;
public class Solution {
public static void insertionSortPart2(int[] ar) {
int key;
int seen;
for (int i = 0 ; i < ar.length-1; i++){
key = ar[i];
seen = i;
while (seen <ar.length-1 && ar[seen+1]<key){
ar[seen]= ar[seen+1];
seen = seen+1;
}
ar[seen]=key;
printArray(ar);
}
}
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int s = in.nextInt();
int[] ar = new int[s];
for(int i=0;i<s;i++){
ar[i]=in.nextInt();
}
insertionSortPart2(ar);
}
private static void printArray(int[] ar) {
for(int n: ar){
System.out.print(n+" ");
}
System.out.println("");
}
}
Input (stdin) 6 1 4 3 5 6 2
Your Output (stdout) 1 4 3 5 6 2 1 3 4 5 6 2 1 3 4 5 6 2 1 3 4 5 6 2 1 3 4 5 2 6
Expected Output 1 4 3 5 6 2 1 3 4 5 6 2 1 3 4 5 6 2 1 3 4 5 6 2 1 2 3 4 5 6 Compiler Message Wrong Answer
You are doing it in wrong way. Read the part 1 again.
Assume that first element is sorted. Then try to insert element one by one in sorted list.
Try this:
public static void insertionSortPart2(int[] ar) {
int key;
int seen;
for (int i = 1 ; i < ar.length; i++){
key = ar[i];
seen = i;
while (seen > 0 && ar[seen-1] > key) {
ar[seen] = ar[seen-1];
seen = seen - 1;
}
ar[seen]=key;
printArray(ar);
}
}
Here is one solution to the Josephus problem (where people are arranged in a circle and every other person is killed until only one remains):
import java.util.ArrayList;
public class test {
public static void main(String[] args) {
ArrayList<Integer> chairArr = new ArrayList<Integer>();
for (int i = 1; i <= 10; i++) {
chairArr.add(i);
}
int result = 0;
for (int i = 1; i < chairArr.size() - 1; i = i + 2) {
chairArr.add(chairArr.get(i));
result = i;
}
System.out.print("Result: " + chairArr.get(result));
}
}
But what if, instead of skipping every other person, we increased the number skipped as we went through? That is, if 10 people were arranged in the circle, persons 1, 3, 6, 10, etc. were killed in that order. I think the modification would come in the i = i + 2 in the for loop, but I'm not sure.
I worked it out on paper, and this is the order of elimination, where asterisks denote the number to be removed:
0 *1* 2 3 4 5 6 7 8 9 10
1 2 *3* 4 5 6 7 8 9 10
2 2 4 5 *6* 7 8 9 10
3 2 4 5 7 8 9 *10*
4 2 4 5 7 *8* 9
5 2 4 5 7 *9*
6 2 4 *5* 7
7 *2* 4 7
8 *4* 7
9 7 <-- Result
Thoughts?
Edit: Tried this modification of the for loop:
for (int j = 2; j < chairArr.size() - 1; j++) {
for (int i = 1; i < chairArr.size() - 1; i = i + j) {
chairArr.add(chairArr.get(i));
result = i;
}
}
This won't work because after the initial pass where j = 2, the inner loop will already have narrowed the list down to one candidate so the outer loop never completes.
I am currently trying to create a nested for Loop statement using java, how do I Create new nested for Loop statement using java which gives the following output:
8
5 5 5 6 5 8 9 5 6 8
7 7 8 7 6 7 8 8 9 7
8 7 6 7 8 7 5 6 8 7
9 9 9 8 9 7 9 8 9 9
7 8 8 7 8 7 8 9 6 8
6 5 6 4 5 6 5 6 6 6
7 8 7 7 6 8 7 8 6 6
5 7 6 7 6 7 6 7 7 7
the above numbers are stored in a text file called data1.txt but need to be displayed properly as ints using a 2D array,
Below is my attempt at the code:
import java.util.*;
import java.io.*;
/**
* class <code>ReadMarks</code> simulates storing student data in a collection.
*
* #author
* #version 09 Feburary 2014
*/
public class ReadMarks
{
/**
* Constructor for objects of class ReadMarks
*/
public ReadMarks()
{
}
/**
* An example of a method - replace this comment with your own
*
*/
public void readMarksData(String fileName) throws FileNotFoundException
{
File dataFile = new File(fileName);
Scanner scanner = new Scanner(dataFile);
while( scanner.hasNext() )
{
String info = scanner.nextLine();
System.out.println(info);
}
scanner.close();
}
for (int i= 0; i <8; i++)
for (int j=1; j<=i; j++)
System.out.print(i*j + "\t");
}
for (int row=1; row<=10; row++)
{
for (int col=1; col<=8; col++)
System.out.print(row*col + "\t");
System.out.println();
}
any answers or replies would be greatly appreciated
In you code, you do not read numbers from file, you just read whole lines and print it. If you want to read all these ints, you should write something like this:
List<Integer> ints = new LinkedList<>();
while (scanner.hasNextInt()) {
ints.add(scanner.nextInt());
}
Now, ints variable holds all ints sequentially read form your file. Then we need to print them. As correctly you've noticed, you will need two loops with nesting. You, however, assumed, that 10 rows and 8 columns. What if it doesn't? And what if we want to reformat our output? Let's rather set the number of columns and we will be printing as many rows, as needed:
int columnCount = 10;
for (int i = 0, l = ints.size(); i < l;) {
for (int c = 0; c < columnCount; c++, i++) {
System.out.printf("%3d", ints.get(i));
}
System.out.println();
}
Now you can just change value of columnCount to reformat output. If you need to print this matrix as a regular square (which not really can be possible, as int count doesn't have to sufficient to form regular square), you can calculate square root of the number of int in the ints list and compare its square to actual length — if those values match, it means you can set the value of columnCount to the square root of int count and be happy with nice square matrix.
My problem occurs during the for loops to read in the values from the file into my scores array. The program reads in and prints the first 6 values or 2 lines of ints, but then I get ArrayIndexOutOfBoundsException: 2
I have no idea why this is stopping there. If I have j<1000, it will read 17 values. Anyway, the file I'm reading in is below (wasn't sure the formatting for a text file).
Any help would be appreciated
Andy Matt Tom
3 2 3
4 4 5
3 3 2
2 2 2
2 4 2
2 3 2
4 4 5
2 3 3
4 3 5
3 3 6
2 2 5
3 3 3
3 3 2
3 2 4
3 2 6
3 4 3
2 3 2
2 2 2
50 52 62
public static void main( String args[] )
{
try
{
if (args.length<1)
{
System.out.printf("\n...You must enter the name of a file\n");
System.exit(0);
}
Scanner infile = new Scanner ( new File(args[0]) );
int par= 3;
int play= 18;
String[] players= new String[play];
int k=0;
int scores[][]= new int[play-1][par-1];
while(infile.hasNext())
{
players[k]=infile.next();
k++;
if (k==play)
break;
}
for(int j=0; j<par; j++)
{
for (int i=0; i<play; i++)
{
scores[j][i]=infile.nextInt();
System.out.println(scores[j][i]);
}
}
}
catch (FileNotFoundException e)
{
System.out.println("Bug");
System.exit(0);
}
}
int scores[][] = new int [play-1][par-1];
Why -1? That's where your AIOOB is coming from.
There are two issues:
int scores[][] = new int[play-1][par-1]; // Why -1 ?
and:
for(int j=0; j<par; j++) // should be 'j < play' as 'j'
// is index to dimension
// with size 'play'
{
for (int i=0; i<play; i++) // should be 'i < par' as 'i' is
// index to dimension with
// size 'par'
{
scores[j][i]=infile.nextInt();
System.out.println(scores[j][i]);
}
}
Actually, there are three issues.
There are only 3 players, not 18
You need a 18x3 array, not a 17x2 array
[i][j] instead of [j][i]
Diff of your code against my modified version (which works like a charm):
22c22
< String[] players= new String[play];
---
> String[] players= new String[par];
24c24
< int scores[][]= new int[play-1][par-1];
---
> int scores[][]= new int[play][par];
32c32
< if (k==play)
---
> if (k==par)
41,42c41,42
< scores[j][i]=infile.nextInt();
< System.out.println(scores[j][i]);
---
> scores[i][j]=infile.nextInt();
> System.out.println(scores[i][j]);