I have to read a sentence, and preserving the order of them,to write the words back, for example: input "I want a donut", output "I tnaw a tunod".
I wrote the code but it but it marks a bug in the for loop, honestly I don't know why.
import java.lang.*;
import java.util.*;
public class Main {
public static void main(String[] args) {
Scanner read = new Scanner(System.in);
System.out.println("Introduce your sentence");
String line;
line = read.nextLine();
int T = line.length();
int Wspace = 0;
int x = 0;
for (int i = 0; i < T; i++)
if(Character.isWhitespace(line.charAt(i)))
x = Wspace++;
for(int i = 0,int l = 0; i < T, l < x-1; i++, l++) //marks bugs here :({
if (!Character.isWhitespace(line.charAt(i)))
arrl[i] = arr[i];
else
i++;
}
}
}
There are 2 problems with your for loop.
1. Defining of int i =0, int l =0;
This should be written as int i =0, l = 0;
When defining in same line, the second int is not needed.
Conditions should not be comma(,) or semicolon(;) separated. We can use the && operator to join both the conditions together. so
i < T, l < x-1;
should either be
i < T && (l < x-1);
Or some other way should be found to represent the condition. Rewriting the loop could be one such way as defined in the other answer.
You cannot simply use the for sentence with twoo variables:
for(int i = 0,int l = 0; i < T, l < x-1; i++, l++
did you try while sentence?
int i = 0, l=0;
while(i<T && l<x-1) {
you have to create memory allocation for your array with new keyword
String arrl[] = new String[T];
import java.lang.*;
import java.util.*;
/**
*
* #author cesargarcia
*/
public class NewClass {
public static void main(String[] args) {
Scanner read = new Scanner(System.in);
System.out.println("Introduce your sentence");
String line;
line = read.nextLine();
int T = line.length();
int Wspace = 0;
int x = 0;
for (int i = 0; i < T; i++) {
if (Character.isWhitespace(line.charAt(i))) {
x = Wspace++;
}
}
String arrl[] = new String[T];
String arr[] = new String[T];
int i = 0, l=0;
while(i<T && l<x-1) {
{
if (!Character.isWhitespace(line.charAt(i))) {
arrl[i] = arr[i];
} else {
i++;
}
}
}
}
}
I am attempting to input the following file into my program in the form of an adjacency matrix.
16
-1,1075,716,792,1425,1369,740,802,531,383,811,2211,661,870,999,772
1075,-1,1015,1770,2403,1662,870,1858,941,1426,1437,3026,1486,211,1463,314
716,1015,-1,928,1483,646,390,1085,185,749,530,2034,1377,821,471,772
792,1770,928,-1,633,1089,1111,246,908,409,495,1447,1317,1565,672,1470
1425,2403,1483,633,-1,9999,1630,752,1432,9999,931,814,1938,2198,1016,2103
1369,1662,646,1089,9999,-1,820,1335,832,9999,605,1839,2030,1468,421,1419
740,870,390,1111,1630,820,-1,1224,360,965,690,2197,1480,750,630,705
802,1858,1085,246,752,1335,1224,-1,1021,442,737,1566,1190,1653,918,1558
531,941,185,908,1432,832,360,1021,-1,685,496,2088,1192,736,616,656
383,1426,749,409,9999,9999,965,442,685,-1,738,1858,1938,1221,926,1126
811,1437,530,495,931,605,690,737,496,738,-1,1631,1472,1232,188,1152
2211,3026,2034,1447,814,1839,2197,1566,2088,1858,1631,-1,2752,2824,1563,2744
661,1486,1377,1317,1938,2030,1480,1190,1192,1938,1472,2752,-1,1281,1660,1183
870,211,821,1565,2198,1468,750,1653,736,1221,1232,2824,1281,-1,1269,109
999,1463,471,672,1016,421,630,918,616,926,188,1563,1660,1269,-1,1220
772,314,772,1470,2103,1419,705,1558,656,1126,1152,2744,1183,109,1220,-1
However, I think I have something wrong with my logic or I'm not using the Scanner correctly. This is my code:
public class Tour
{
public static final int N = 16;
public static final int INF = Integer.MAX_VALUE;
public static void printGrid(int[][] adjMat)
{
for(int i = 0; i < 16; i++)
{
for(int j = 0; j < 16; j++)
{
if(adjMat[i][j] == INF)
System.out.printf("%5s", 0);
else
System.out.printf("%5d", adjMat[i][j]);
}
System.out.println();
}
}
public static void main(String[] args) throws IOException
{
File file = new File("american_tour.dat");
Scanner scanner = new Scanner(file);
int[][] adjMat = new int[N][N];
for(int i = 0, n = scanner.nextInt(); i < n; i++)
for(int j = 0; j < n; j++)
adjMat[i][j] = n;
scanner.close();
printGrid(adjMat);
}
}
Could someone show me how to properly input the data from the file into an adjacency matrix?
Improving Mouad's answer, using the scanner's built in support for custom delimiters:
Scanner scanner = new Scanner(file);
scanner.useDelimiter("[\\s,]+");
int N = scanner.nextInt();
int[][] adjMat = new int[N][N];
for(int i=0; i < N; i++) {
for (int j=0; j < N; j++) {
adjMat[i][j] = scanner.nextInt();
}
}
scanner.close();
As your data does not respect a specific pattern for delimiters, try this instead :
public static void main(String[] args) throws FileNotFoundException {
File file = new File("E:\\american_tour.dat");
Scanner scanner = new Scanner(file);
//N in the example equals 16
int N = scanner.nextInt();
//skip the first line
scanner.nextLine();
int[][] adjMat = new int[N][N];
for(int i = 0; i < N; i++){
String[] lines = scanner.nextLine().split(",");
for (int j=0; j<lines.length; j++) {
adjMat[i][j] = Integer.parseInt(lines[j]);
}
}
scanner.close();
}
I encountered a question on hackerrank.
https://www.hackerrank.com/challenges/countingsort4
My first attempt passed all the test cases except the last one, due to timeout.
After failed to come up with a more efficient algorithm, I improved the code by using StringBuilder instead of concatenating Strings directly. This brought the running time from more than 5 sec to 3.5 sec.
My question is that is there any other way that I can improve the running time?
Thanks.
The following is my code.
public class Solution {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int N = scanner.nextInt();
scanner.nextLine();
int[] oriNum = new int[N];
String[] oriStr = new String[N];
int[] count = new int[100];
int[] indices = new int[100];
int[] output = new int[N];
// save the originals and the count array
for (int i = 0; i < N; i++) {
oriNum[i] = scanner.nextInt();
oriStr[i] = scanner.nextLine().trim();
count[oriNum[i]]++;
}
// accumulate the count array
indices[0] = 0;
for (int i = 1; i < 100; i++) {
indices[i] = indices[i-1] + count[i-1];
}
// output order
for (int i = 0; i < N; i++) {
int num = oriNum[i];
output[indices[num]++] = i;
}
int bar = N/2;
StringBuilder sb = new StringBuilder();
for (int i = 0; i < N; i++) {
int index = output[i];
if (index < bar)
sb.append("- ");
else
sb.append(oriStr[index]+ " ");
}
System.out.println(sb.toString());
}
}
You should try a plain buffered reader instead of Scanner. Scanner is surprisingly slow and I have participated in programming competitions where Scanner was the sole reason for "time limit exceeded".
import java.io.*;
import java.util.*;
import java.text.*;
import java.math.*;
import java.util.regex.*;
public class Solution
{
public static void main(String[] args)throws Exception
{
BufferedReader in=new BufferedReader(new InputStreamReader(System.in));
int n=Integer.parseInt(in.readLine());
int[] c=new int[100];
String[][] dt=new String[100][10300];
for(int i=0;i<n;i++)
{
String[] str=in.readLine().split(" ");
int val=Integer.parseInt(str[0]);
if(i<n/2)
dt[val][c[val]]="-";
else
dt[val][c[val]]=str[1];
c[val]++;
}
StringBuilder sb=new StringBuilder("");
for(int i=0;i<100;i++)
if(i<n)
for(int k=0;k<c[i];k++)
if(dt[i][k]!=null)
sb.append(dt[i][k]+" ");
else break;
System.out.println(sb.toString());
}
}
This was my approach to problem. (it is in c++).
void counting_sort(vector<int> &arr, int size, vector<vector<string> > foo, vector<int> first_half)
{
int max = *max_element(arr.begin(), arr.end());
int min = *min_element(arr.begin(), arr.end());
int range = max - min + 1;
int count[range] = {0};
// counting frequency of numbers in array
for (int i = 0; i < size; i++)
{
count[arr[i] - min]++;
}
// calculating cumulative sum
for (int i = 1; i < range; i++)
{
count[i] += count[i - 1];
}
vector<vector<string> > output(size);
// making the new sorted array
for (int i = size - 1; i >= 0; i--) // traversing from backward for stability
{
output[count[arr[i]-min] - 1] = foo[i];
count[arr[i]-min]--;
}
// copying the sorted array in original array
int j=0;
for (int i = 0; i < size; i++)
{
if(stoi(output[i][0]) == first_half[j])
{
cout << "- ";
j++;
}
else
{
cout << output[i][1] << ' ';
}
}
}
// Complete the countSort function below.
void countSort(vector<vector<string>> arr) {
vector<int> num;
vector<int> first_half;
for(int i=0; (unsigned)i<arr.size(); i++)
{
num.push_back(stoi(arr[i][0]));
if(i < ((unsigned)arr.size()/2))
{
first_half.push_back(stoi(arr[i][0]));
}
}
sort(first_half.begin(), first_half.end());
counting_sort(num, num.size(), arr, first_half);
}
I've been trying to solve the warmup challenges on Hackerrank. For this particular challenge - https://www.hackerrank.com/challenges/cut-the-sticks - I've written some code, and although it seems logically correct to me, I'm not getting the right answer.
My Code -
import java.util.*;
public class Solution {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
int lengths[] = new int[n];
List<Integer> output = new LinkedList<Integer>();
for (int i = 0; i < n; i++)
lengths[i] = sc.nextInt();
sc.close();
Arrays.sort(lengths);
for (int i = 0; i < n; i++) {
if (lengths[i] == 0)
continue;
else {
output.add(n - i);
for (int j = i; j < n; j++) { // This loop isn't working like it should
lengths[j] -= lengths[i];
// System.out.print(lengths[j] + " "); // For debugging purposes
}
// System.out.println("");
}
}
for (int i = 0; i < output.size(); i++)
System.out.println(output.get(i));
}
}
For the following input -
6
5 4 4 2 8 2
The output I get is -
6
5
4
3
2
1
The correct output should be -
6
4
2
1
I tried to display the values of the lengths array throughout the runs of the for loop marked in the code (with a comment), and this is what i get for the same inputs as above -
0 2 4 4 5 8
0 4 4 5 8
0 4 5 8
0 5 8
0 8
0
6
5
4
3
2
1
I'm totally stumped as to why this would happen.
The problem is here:
lengths[j] -= lengths[i];
When i == j is true, this changes the value of lengths[i]. You need to save that value first.
final int v = lengths[i];
for (int j = i; j < n; j++) {
lengths[j] -= v;
}
Had solved it sometime back.
Here's a version of answer, using a do while loop
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
int size = scan.nextInt();
int sticks [] = new int[size];
for (int i = 0; i < size; i++){
sticks[i] = scan.nextInt();
}
Arrays.sort(sticks);
do {
int count =0;
int leastLength = sticks[0];
for (int j=0; j < sticks.length; j++){
sticks[j] = sticks[j] - leastLength;
count++;
}
System.out.println(count);
List<Integer> resizeArray = new LinkedList<Integer>();
for ( int i=0; i< sticks.length; i++){
if (sticks[i] != 0){
resizeArray.add(sticks[i]);
}
}
int temp[] = new int[resizeArray.size()];
for (int i = 0; i < resizeArray.size(); i ++){
temp[i] = resizeArray.get(i);
}
sticks = temp;
} while (sticks.length > 0);
}
package com.omt.learn.algo;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Arrays;
public class CutTheSticks2 {
public static void main(String s[]) throws NumberFormatException, IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
short N = Short.parseShort(br.readLine());
short[] A = new short[N];
N = 0;
for (String str : br.readLine().split(" ")) {
A[N++] = Short.parseShort(str);
}
Arrays.sort(A);
StringBuffer sb = new StringBuffer();
System.out.println(N);
for (int i = 1; i < N; i++) {
if (A[i - 1] != A[i]) {
sb.append((N - i) + "\n");
}
}
// OUTPUT
System.out.print(sb);
}
}
import java.io.*;
import java.util.*;
import java.text.*;
import java.math.*;
import java.util.regex.*;
public class Solution {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int n = in.nextInt();
int arr[] = new int[n];
for(int arr_i=0; arr_i < n; arr_i++){
arr[arr_i] = in.nextInt();
}
int count = 2;
int min=1000;
for(int arr_i=0;count !=1 ; arr_i++){ // read
count = 0;
for(int arr_j=0; arr_j < n; arr_j++)// find min
{ if(min >arr[arr_j] && arr[arr_j]!=0)
min=arr[arr_j];
}
for(int arr_k=0; arr_k < n; arr_k++)// sub
{
if(arr[arr_k]>=min)
{ count++;
arr[arr_k]= arr[arr_k] - min;
}
}
System.out.println(count);
}
}
}
This is a working solution in JavaScript. Took me a while to realize that the sort() in JavaScript performs a string comparison in alphabetical order.
function sortNumbers(a, b) {
return a - b;
}
function cutSticks(arr){
var smallestStick = 0;
arr = arr.sort(sortNumbers);
while(arr.length > 0) {
console.log(arr.length);
smallestStick = arr[0];
var newArray = [];
arr.forEach(function (val) {
var newValue = val - smallestStick;
if (newValue > 0) {
newArray.push(newValue);
}
});
arr = newArray;
}
}
function main() {
var n = parseInt(readLine());
arr = readLine().split(' ');
arr = arr.map(Number);
cutSticks(arr);
}
Hope it helps!
Java Version. Passed all tests, but not sure if is best performance.
static int[] cutTheSticks(int[] arr) {
List<Integer> sticks = Arrays.stream(arr).boxed().collect(toList());
List<Integer> cuts = new ArrayList<>();
while (true) {
int min = sticks.stream().mapToInt(Integer::valueOf).min().getAsInt();
Iterator it2 = sticks.iterator();
int cuted = 0;
List<Integer> temp = new ArrayList<>();
while (it2.hasNext()) {
int v = (int) it2.next();
if (v == min) {
it2.remove();
cuted++;
} else {
int nv = v - min;
it2.remove();
temp.add(nv);
cuted++;
}
}
cuts.add(cuted);
sticks.addAll(temp);
if (sticks.isEmpty()) {
break;
}
}
return cuts.stream().mapToInt(Integer::valueOf).toArray();
}