How to initialize instance variables in setup()? - hadoop

This should be a simple question, but I'm struggling with it. Everything in my code is working except for initializing the parameter values for "train_rows" and "cols" read in from the Configuration file.
I set up logging to display the values of "train_rows" and "cols" within the setup() method, and the values were correct. However, when I tried the same thing within the map() method, both values showed 0. What am I doing wrong?
import java.io.File;
import java.io.IOException;
import java.io.FileNotFoundException;
import java.util.Scanner;
import org.apache.log4j.Logger;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.io.IntWritable;
import org.apache.hadoop.io.LongWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.Mapper;
public class KNNMapper extends Mapper<LongWritable, Text, IntWritable, IntWritable> {
private static final Logger sLogger = Logger.getLogger(KNNMapper.class);
private int[][] train_vals;
private int[] train_label_vals;
private int train_rows;
private int test_rows;
private int cols;
#Override
public void setup(Context context) throws IOException, InterruptedException {
Configuration conf = context.getConfiguration();
train_rows = conf.getInt("rows", -1);
cols = conf.getInt("columns", -1);
//just changed this
//int[][] train_vals = new int[train_rows][cols];
//int[] train_label_vals = new int[train_rows];
train_vals = new int[train_rows][cols];
train_label_vals = new int[train_rows];
// read train csv, parse, and store into 2d int array
Scanner myScan;
try {
File trainfile = new File("train_sample.csv");
if (!trainfile.exists()) {
throw new IllegalArgumentException("train file didn't load");
}
myScan = new Scanner(trainfile);
//Set the delimiter used in file
myScan.useDelimiter("[,\r\n]+");
//Get all tokens and store them in some data structure
//I am just printing them
for(int row = 0; row < train_rows; row++) {
for(int col = 0; col < cols; col++) {
train_vals[row][col] = Integer.parseInt(myScan.next().toString());
}
}
myScan.close();
} catch (FileNotFoundException e) {
System.out.print("Error: Train file execution did not work.");
}
// read train_labels csv, parse, and store into 2d int array
try {
File trainlabels = new File("train_labels.csv");
if (!trainlabels.exists()) {
throw new IllegalArgumentException("train labels didn't load");
}
myScan = new Scanner(trainlabels);
//Set the delimiter used in file
myScan.useDelimiter("[,\r\n]+");
//Get all tokens and store them in some data structure
//I am just printing them
for(int row = 0; row < train_rows; row++) {
train_label_vals[row] = Integer.parseInt(myScan.next().toString());
if(row < 10) {
System.out.println(train_label_vals[row]);
}
}
myScan.close();
} catch (FileNotFoundException e) {
System.out.print("Error: Train Labels file not found.");
}
}
#Override
public void map(LongWritable key, Text value, Context context)
throws IOException, InterruptedException {
// setup() gave us train_vals & train_label_vals.
// Each line in map() represents a test observation. We iterate
// through every train_val row to find nearest L2 match, then
// return a key/value pair of <observation #,
// convert from Text to String
System.out.println("I'm in the map!");
String line = value.toString();
double distance;
double best_distance = Double.POSITIVE_INFINITY;
int col_num;
int best_digit = -1;
IntWritable rowId = null;
int i;
IntWritable rowNum;
String[] pixels;
System.out.println("Number of train rows:" + train_rows);
System.out.println("Number of columns:" + cols);
// comma delimited files, split on commas
// first we find the # of rows
pixels = line.split(",");
rowId = new IntWritable(Integer.parseInt(pixels[0]));
System.out.println("working on row " + rowId);
best_distance = Double.POSITIVE_INFINITY;
for (i = 0; i < train_rows; i++) {
distance = 0.0;
col_num = 0;
for (int j = 1; j < cols; j++) {
distance += (Integer.parseInt(pixels[j]) - train_vals[i][j-1])^2;
}
if (distance < best_distance) {
best_distance = distance;
best_digit = train_label_vals[i];
}
}
System.out.println("And we're out of the loop baby yeah!");
context.write(rowId, new IntWritable(best_digit));
System.out.println("Mapper done!");
}
}

i doubt this , assuming you are scanning the file in hdfs.
you used:
import java.io.File; File trainfile = new File("train_sample.csv");
in hadoop this is how we check for a file in hdfs :
try {
FileSystem fs = FileSystem.get(context.getConfiguration());
if (fs.exists(new Path("/user/username/path/of/file/inhdfs"))) {
System.out.println("File exists");
}
} catch (IOException e) {
e.printStackTrace();
}

Related

Can't get my String switch statement to hit anything but default

I am trying to use a switch statement to pass a LinkedHashMap to the correct class constructor for a school project(I just added the rest of the code).
The code reads takes in a txt file and based off the first word in the text sends the hash map.
I can't seem to get a hit on the case report I am testing.
I have even tried just making everything into an if-else-if structure,
and that still didn't work out,
I've tried using a private enum method to no avail.
I am at a loss here.
I am running Java 8.
I am open to any suggestion on optimizing the code as well.
Thanks.
package linkedlist;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JButton;
import javax.swing.JFileChooser;
import javax.swing.JLabel;
/**
*
* #author admin
*/
public class TextReaderGUI extends javax.swing.JFrame {
JFileChooser fileChooser = new JFileChooser();
String rawText;
String[] text;
public String listType;
private JButton fileChooserButton;
private JLabel statusLabel;
/**
* Creates new form TextReaderGUI
*/
public TextReaderGUI() {
initComponents();
}
/**
* This method is called from within the constructor to initialize the form.
* WARNING: Do NOT modify this code. The content of this method is always
* regenerated by the Form Editor.
*/
#SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">
private void initComponents() {
fileChooserButton = new javax.swing.JButton();
statusLabel = new javax.swing.JLabel();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
fileChooserButton.setText("File Chooser");
fileChooserButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
fileChooserButtonActionPerformed(evt);
}
});
statusLabel.setText("Status: ");
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING).addGroup(layout
.createSequentialGroup()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup().addGap(14, 14, 14).addComponent(fileChooserButton))
.addGroup(layout.createSequentialGroup().addGap(36, 36, 36).addComponent(statusLabel)))
.addContainerGap(264, Short.MAX_VALUE)));
layout.setVerticalGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup().addGap(16, 16, 16).addComponent(fileChooserButton)
.addGap(18, 18, 18).addComponent(statusLabel).addContainerGap(221, Short.MAX_VALUE)));
pack();
}// </editor-fold>
private void fileChooserButtonActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
try {
int returnVal = fileChooser.showOpenDialog(this);
if (returnVal == JFileChooser.APPROVE_OPTION) {
File file = fileChooser.getSelectedFile();
rawText = "";
BufferedReader reader = new BufferedReader(new FileReader(file));
StringBuilder stringb = new StringBuilder();
String s;
while ((s = reader.readLine()) != null) {
stringb.append(s);
stringb.append("\n"); // this makes sure that java sees when a new line has started
}
rawText = stringb.toString();
statusLabel.setText("Status: " + file.getName());
}
} catch (IOException e) {
statusLabel.setText("Status" + e);
}
text = rawText.split("\n"); // creating a string array split at each line break
Map<String, String> lines = new LinkedHashMap<>();
for (int i = 0; i < text.length; i++) { // this sets the first word of the line = key
String[] currentLine = text[i].split("\\s+"); // splits the words in the current line to an array
if (i == 0) {
listType = currentLine[0].replaceAll("\n", "").replaceAll("\\s+", ""); // determines listType to pass
}
if (currentLine.length > 1 && i > 0) {
lines.put(currentLine[0] + " " + i, currentLine[1]); // if two words exist on a line
// the first is the key second is the value
} else if (currentLine.length == 1 && i > 0) { // keeps list type out of key values
lines.put(currentLine[0] + " " + i, ""); // " " + i is used to ensure that each command is unique key
}
}
lines.keySet().forEach((name) -> {// Testing to see if document was correctly placed into the HashMap
String key = name;
String value = lines.get(name);
System.out.println(key + " " + value + "\n");
});
System.out.println(listType); // testing to see if list type was correctly stored
switch (listType) {
case "stack":
Stack stack = new Stack((LinkedHashMap) lines);
break;
case "queue":
Queue queue = new Queue((LinkedHashMap) lines);
break;
case "dll":
Dll dll = new Dll((LinkedHashMap) lines);
break;
case "sll":
System.out.println("almost there");
Sll sll = new Sll((LinkedHashMap) lines);
break;
case "cll":
Cll cll = new Cll((LinkedHashMap) lines);
break;
default:
System.out.println("something went wrong here");
break;
}
}
}

JavaFX: When the user presses the mouse within a panel, its color should be changed randomly?

I am having trouble with my code. I had to make a chessboard for a previous problem. Now I have to use that same code to display 8X8 grids which are initially white. Once clicked on, they should, they should change color randomly. Can someone please help, here is a copy of my code.
import javafx.application.Application;
import javafx.geometry.HPos;
import javafx.geometry.VPos;
import javafx.scene.Scene;
import javafx.scene.control.Control;
import javafx.scene.layout.ColumnConstraints;
import javafx.scene.layout.GridPane;
import javafx.scene.layout.Priority;
import javafx.scene.layout.RowConstraints;
import javafx.scene.layout.StackPane;
import javafx.stage.Stage;
import javafx.scene.layout.Pane;
import javafx.scene.input.MouseEvent;
import javafx.scene.shape.Rectangle;
import javafx.event.EventHandler;
import javafx.scene.paint.Paint;
import javafx.scene.paint.Color;
public class ChessBoardColor extends Application {
#Override
public void start(Stage primaryStage) {
GridPane pane = new GridPane();
int size = 8 ;
for (int row = 0; row < size; row++) {
for (int color = 0; color < size; color ++) {
StackPane panel = new StackPane();
String boxcolor ;
if ((row + color) % 2 == 0) {
boxcolor = "red";
} else {
boxcolor = "black";
}
panel.setStyle("-fx-background-color:#FFFFFF;");
pane.add(panel, color, row);
pane.setOnMouseClicked(e -> {
pane.setStroke();
});
}
}
}
for (int i = 0; i < size; i++) {
pane.getColumnConstraints().add(new ColumnConstraints(5, Control.USE_COMPUTED_SIZE, Double.POSITIVE_INFINITY, Priority.ALWAYS, HPos.CENTER, true));
pane.getRowConstraints().add(new RowConstraints(5, Control.USE_COMPUTED_SIZE, Double.POSITIVE_INFINITY, Priority.ALWAYS, VPos.CENTER, true));
}
primaryStage.setScene(new Scene(pane, 500, 500));
primaryStage.show();
public static void main(String[] args) {
launch(args);
}
}
look at this code simply find the node where the user click and apply style like you know:
public class ChessBoardColor extends Application {
#Override
public void start(Stage primaryStage) {
GridPane pane = new GridPane();
int size = 8;
for (int row = 0; row < size; row++) {
for (int color = 0; color < size; color++) {
StackPane panel = new StackPane();
String boxcolor; //initial box color = "white" if you want it white initialy
if ((row + color) % 2 == 0) {//I suppose it's your chessboard color
boxcolor = "red";
} else {
boxcolor = "black";
}
panel.setStyle("-fx-background-color:" + boxcolor + ";");
pane.add(panel, color, row);
pane.setOnMouseClicked(e -> {
Node target = (Node) e.getTarget(); // you find where the user click
if (target instanceof StackPane) {
String radomColor = getRandomColor(); // choose a random color
((StackPane) target).setStyle("-fx-background-color:" + radomColor + ";"); // apply it like you already know
}
});
}
}
for (int i = 0; i < size; i++) {
pane.getColumnConstraints().add(new ColumnConstraints(5, Control.USE_COMPUTED_SIZE,
Double.POSITIVE_INFINITY, Priority.ALWAYS, HPos.CENTER, true));
pane.getRowConstraints().add(new RowConstraints(5, Control.USE_COMPUTED_SIZE, Double.POSITIVE_INFINITY,
Priority.ALWAYS, VPos.CENTER, true));
}
primaryStage.setScene(new Scene(pane, 500, 500));
primaryStage.show();
}
private String getRandomColor() { // simple random color generator
String colors[] = new String[] {"blue", "yellow", "green", "purple"};
Random ran = new Random();
int randomColourIndex = ran.nextInt(4);
return colors[randomColourIndex];
}
public static void main(String[] args) {
launch(args);
}
}

TableView#scrollTo(int index) but show row in bottom

I would like to scroll down to a specific row in a TableView. TableView#scrollTo(int index) puts the row on the specified index in the top of the view, but I would like the specified index to be in the bottom of the view. This is because the specified row will always be the row below the currently focused row for me, and I just want to scroll as much as needed to show that next row. I.e: I want the behaviour you get when you change the row selection by using the UP and DOWN keys. Is this possible? Here's an MCVE:
import javafx.application.Application;
import javafx.beans.property.SimpleStringProperty;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.TableColumn;
import javafx.scene.control.TableView;
import javafx.scene.layout.VBox;
import javafx.stage.Stage;
public class TestScrollToTable extends Application {
#Override
public void start(Stage stage) {
TableView<ObservableList<String>> table = new TableView<>();
table.getSelectionModel().setCellSelectionEnabled(true);
ObservableList<String> columns = FXCollections.observableArrayList();
for (int i = 0; i < 10; i++) {
columns.add("column " + i);
}
ObservableList<ObservableList<String>> data = FXCollections.observableArrayList();
for (int rowIndex = 0; rowIndex < 100; rowIndex++) {
ObservableList<String> row = FXCollections.observableArrayList();
for (int colIndex = 0; colIndex < columns.size(); colIndex++) {
row.add("row" + rowIndex + "col" + colIndex);
}
data.add(row);
}
for (int colIndex = 0; colIndex < columns.size(); colIndex++) {
final int j = colIndex;
TableColumn<ObservableList<String>, String> col = new TableColumn<ObservableList<String>, String>(
columns.get(colIndex));
col.setCellValueFactory(param -> new SimpleStringProperty(param.getValue().get(j)));
table.getColumns().add(col);
}
table.setItems(data);
Button scrollToButton = new Button("Focus next row");
scrollToButton.setOnAction(e -> {
if (table.getFocusModel().getFocusedItem() != null) {
int nextIndex = table.getFocusModel().getFocusedIndex()+1;
table.getFocusModel().focus(nextIndex);
table.scrollTo(nextIndex);
}
});
VBox root = new VBox();
root.getChildren().addAll(table, scrollToButton);
stage.setScene(new Scene(root));
stage.show();
}
public static void main(String[] args) {
launch();
}
}
you can use this function
private void scrollToUpAndBottom(int indexToScroll, VirtualFlow vf) {//scroll to up
if (indexToScroll < vf.getFirstVisibleCell().getIndex()) {
TableView.this.scrollTo(indexToScroll);
} else if (indexToScroll > vf.getLastVisibleCell().getIndex()) {//scroll to down
int delta = vf.getLastVisibleCell().getIndex() - vf.getFirstVisibleCell().getIndex();
TableView.this.scrollTo(indexToScroll - delta + 2); // +2 is margin
}
}
to get virtualFlow from TableView, you can use TableViewSkin which has a protected attribute "flow" so you have to create your own skin which make this attribute pulic
public VirtualFlow getVirtualFlow(){ return flow;}

Overlap two audio files

Please someone tell me how to overlap two Audio files and generate single audio file from them. I am trying the following code but I am unable to open saved file.
package com.example.audiomix;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import android.app.Activity;
import android.media.AudioFormat;
import android.media.AudioManager;
import android.media.AudioTrack;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
public class MainActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// MediaPlayer mediaPlayer=MediaPlayer.create(getApplicationContext(),getAssets()+"")
try {
mixSound();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
private void mixSound() {
try {
AudioTrack audioTrack = new AudioTrack(AudioManager.STREAM_MUSIC, 44100, AudioFormat.CHANNEL_OUT_STEREO, AudioFormat.ENCODING_PCM_16BIT, 44100, AudioTrack.MODE_STREAM);
// Uri url = Uri.parse("android.resource://" + getPackageName() + "/" + R.raw.one);
// System.out.println("MainActivity.mixSound() url1"+url.toString());
// File file = new File(url.toString());
// Uri url2 = Uri.parse("android.resource://" + getPackageName() + "/" + R.raw.two);
// System.out.println("MainActivity.mixSound() url1"+url2.toString());
// File file2 = new File(url2.toString());
// InputStream in1=new FileInputStream(file);
// InputStream in2=new FileInputStream(file2);
// int rid = getResources().getIdentifier(getPackageName() + ":raw/one.mp3" , null, null);
// //get the file as a stream
// InputStream in1 = getResources().openRawResource(rid);
//// InputStream in1=new FileInputStream("");
//
// int rid2 = getResources().getIdentifier(getPackageName() + ":raw/two.mp3" , null, null);
// //get the file as a stream
// InputStream in2 = getResources().openRawResource(rid2);
//
//// InputStream in2=new FileInputStream(getResources().openRawResource(R.raw.one).toString());
InputStream in1 = getApplicationContext().getResources().openRawResource(R.raw.media);
InputStream in2 = getApplicationContext().getResources().openRawResource(R.raw.media1);
byte[] music1 = null;
music1= new byte[in1.available()];
music1=convertStreamToByteArray(in1);
in1.close();
byte[] music2 = null;
music2= new byte[in2.available()];
music2=convertStreamToByteArray(in2);
in2.close();
byte[] output = new byte[music2.length];
audioTrack.play();
int j=0;
for(int i=0; i < output.length-1; i++){
float mixed;
if(j<music1.length-1){
float samplef1 = music1[j] / 128.0f; // 2^7=128
float samplef2 = music2[i] / 128.0f;
mixed = samplef1 + samplef2;
j++;
}else{
float samplef2 = music2[i] / 128.0f;
mixed = samplef2;
}
float samplef1 = music1[j] / 128.0f; // 2^7=128
float samplef2 = music2[i] / 128.0f;
mixed = samplef1 + samplef2;
// reduce the volume a bit:
mixed *= 0.8;
// hard clipping
if (mixed > 1.0f) mixed = 1.0f;
if (mixed < -1.0f) mixed = -1.0f;
byte outputSample = (byte)(mixed * 128.0f);
output[i] = outputSample;
} //for loop
audioTrack.write(output, 0, output.length);
//convert array of bytes into file
FileOutputStream fileOuputStream =
new FileOutputStream(Environment.getExternalStorageDirectory()+"/abc.wav");
fileOuputStream.write(output);
fileOuputStream.close();
System.out.println("MainActivity.mixSound()==>Done");
System.out.println("Done");
}catch(Exception e){
// e.printStackTrace();
System.out.println("MainActivity.mixSound()==>"+e);
}
}
public static byte[] convertStreamToByteArray(InputStream is) throws IOException {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
byte[] buff = new byte[10240];
int i = Integer.MAX_VALUE;
while ((i = is.read(buff, 0, buff.length)) > 0) {
baos.write(buff, 0, i);
}
return baos.toByteArray(); // be sure to close InputStream in calling function
}
}
I have tried to first convert audio file into byte array. Then I am saving it on SD card.
The generated file is saved but when I try to play the saved file it is not playing.
That's because both byte arrays have raw audio bytes and headers, so when you mix them you should get one crappy audio file. But you don't. That means that files you are mixing aren't ones with same properties in other words their formats are different.

What is the fastest way to read from standard input in Scala? [duplicate]

I am reading bunch of integers separated by space or newlines from the standard in using Scanner(System.in).
Is there any faster way of doing this in Java?
Is there any faster way of doing this in Java?
Yes. Scanner is fairly slow (at least according to my experience).
If you don't need to validate the input, I suggest you just wrap the stream in a BufferedInputStream and use something like String.split / Integer.parseInt.
A small comparison:
Reading 17 megabytes (4233600 numbers) using this code
Scanner scanner = new Scanner(System.in);
while (scanner.hasNext())
sum += scanner.nextInt();
took on my machine 3.3 seconds. while this snippet
BufferedReader bi = new BufferedReader(new InputStreamReader(System.in));
String line;
while ((line = bi.readLine()) != null)
for (String numStr: line.split("\\s"))
sum += Integer.parseInt(numStr);
took 0.7 seconds.
By messing up the code further (iterating over line with String.indexOf / String.substring) you can get it down to about 0.1 seconds quite easily, but I think I've answered your question and I don't want to turn this into some code golf.
I created a small InputReader class which works just like Java's Scanner but outperforms it in speed by many magnitudes, in fact, it outperforms the BufferedReader as well. Here is a bar graph which shows the performance of the InputReader class I have created reading different types of data from standard input:
Here are two different ways of finding the sum of all the numbers coming from System.in using the InputReader class:
int sum = 0;
InputReader in = new InputReader(System.in);
// Approach #1
try {
// Read all strings and then parse them to integers (this is much slower than the next method).
String strNum = null;
while( (strNum = in.nextString()) != null )
sum += Integer.parseInt(strNum);
} catch (IOException e) { }
// Approach #2
try {
// Read all the integers in the stream and stop once an IOException is thrown
while( true ) sum += in.nextInt();
} catch (IOException e) { }
If you asking from competitive programming point of view, where if the submission is not fast enough, it will be TLE.
Then you can check the following method to retrieve String from System.in.
I have taken from one of the best coder in java(competitive sites)
private String ns()
{
int b = skip();
StringBuilder sb = new StringBuilder();
while(!(isSpaceChar(b))){ // when nextLine, (isSpaceChar(b) && b != ' ')
sb.appendCodePoint(b);
b = readByte();
}
return sb.toString();
}`
You can read from System.in in a digit by digit way. Look at this answer: https://stackoverflow.com/a/2698772/3307066.
I copy the code here (barely modified). Basically, it reads integers, separated by anything that is not a digit. (Credits to the original author.)
private static int readInt() throws IOException {
int ret = 0;
boolean dig = false;
for (int c = 0; (c = System.in.read()) != -1; ) {
if (c >= '0' && c <= '9') {
dig = true;
ret = ret * 10 + c - '0';
} else if (dig) break;
}
return ret;
}
In my problem, this code was approx. 2 times faster than using StringTokenizer, which was already faster than String.split(" ").
(The problem involved reading 1 million integers of up to 1 million each.)
StringTokenizer is a much faster way of reading string input separated by tokens.
Check below example to read a string of integers separated by space and store in arraylist,
String str = input.readLine(); //read string of integers using BufferedReader e.g. "1 2 3 4"
List<Integer> list = new ArrayList<>();
StringTokenizer st = new StringTokenizer(str, " ");
while (st.hasMoreTokens()) {
list.add(Integer.parseInt(st.nextToken()));
}
In programming perspective this customized Scan and Print class is way better than Java inbuilt Scanner and BufferedReader classes.
import java.io.InputStream;
import java.util.InputMismatchException;
import java.io.IOException;
public class Scan
{
private byte[] buf = new byte[1024];
private int total;
private int index;
private InputStream in;
public Scan()
{
in = System.in;
}
public int scan() throws IOException
{
if(total < 0)
throw new InputMismatchException();
if(index >= total)
{
index = 0;
total = in.read(buf);
if(total <= 0)
return -1;
}
return buf[index++];
}
public int scanInt() throws IOException
{
int integer = 0;
int n = scan();
while(isWhiteSpace(n)) /* remove starting white spaces */
n = scan();
int neg = 1;
if(n == '-')
{
neg = -1;
n = scan();
}
while(!isWhiteSpace(n))
{
if(n >= '0' && n <= '9')
{
integer *= 10;
integer += n-'0';
n = scan();
}
else
throw new InputMismatchException();
}
return neg*integer;
}
public String scanString()throws IOException
{
StringBuilder sb = new StringBuilder();
int n = scan();
while(isWhiteSpace(n))
n = scan();
while(!isWhiteSpace(n))
{
sb.append((char)n);
n = scan();
}
return sb.toString();
}
public double scanDouble()throws IOException
{
double doub=0;
int n=scan();
while(isWhiteSpace(n))
n=scan();
int neg=1;
if(n=='-')
{
neg=-1;
n=scan();
}
while(!isWhiteSpace(n)&& n != '.')
{
if(n>='0'&&n<='9')
{
doub*=10;
doub+=n-'0';
n=scan();
}
else throw new InputMismatchException();
}
if(n=='.')
{
n=scan();
double temp=1;
while(!isWhiteSpace(n))
{
if(n>='0'&&n<='9')
{
temp/=10;
doub+=(n-'0')*temp;
n=scan();
}
else throw new InputMismatchException();
}
}
return doub*neg;
}
public boolean isWhiteSpace(int n)
{
if(n == ' ' || n == '\n' || n == '\r' || n == '\t' || n == -1)
return true;
return false;
}
public void close()throws IOException
{
in.close();
}
}
And the customized Print class can be as follows
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.OutputStreamWriter;
public class Print
{
private BufferedWriter bw;
public Print()
{
this.bw = new BufferedWriter(new OutputStreamWriter(System.out));
}
public void print(Object object)throws IOException
{
bw.append("" + object);
}
public void println(Object object)throws IOException
{
print(object);
bw.append("\n");
}
public void close()throws IOException
{
bw.close();
}
}
You can use BufferedReader for reading data
BufferedReader inp = new BufferedReader(new InputStreamReader(System.in));
int t = Integer.parseInt(inp.readLine());
while(t-->0){
int n = Integer.parseInt(inp.readLine());
int[] arr = new int[n];
String line = inp.readLine();
String[] str = line.trim().split("\\s+");
for(int i=0;i<n;i++){
arr[i] = Integer.parseInt(str[i]);
}
And for printing use StringBuffer
StringBuffer sb = new StringBuffer();
for(int i=0;i<n;i++){
sb.append(arr[i]+" ");
}
System.out.println(sb);
Here is the full version fast reader and writer. I also used Buffering.
import java.io.*;
import java.util.*;
public class FastReader {
private static StringTokenizer st;
private static BufferedReader in;
private static PrintWriter pw;
public static void main(String[] args) throws IOException {
in = new BufferedReader(new InputStreamReader(System.in));
pw = new PrintWriter(new BufferedWriter(new OutputStreamWriter(System.out)));
st = new StringTokenizer("");
pw.close();
}
private static int nextInt() throws IOException {
return Integer.parseInt(next());
}
private static long nextLong() throws IOException {
return Long.parseLong(next());
}
private static double nextDouble() throws IOException {
return Double.parseDouble(next());
}
private static String next() throws IOException {
while(!st.hasMoreElements() || st == null){
st = new StringTokenizer(in.readLine());
}
return st.nextToken();
}
}
Reading from disk, again and again, makes the Scanner slow. I like to use the combination of BufferedReader and Scanner to get the best of both worlds. i.e. speed of BufferredReader and rich and easy API of the scanner.
Scanner scanner = new Scanner(new BufferedReader(new InputStreamReader(System.in)));

Resources