Sorting BigDecimal - java

What is the problem with this BigDecimalSorting? The code takes in numbers as string and then converts it to BigDecimal and then sort and print the sorted BigDecimals.
import java.math.BigDecimal;
import java.util.*;
class Solution {
public static void main(String []argh){
Scanner sc= new Scanner(System.in);
int n=sc.nextInt();
String []s=new String[n];
BigDecimal a[] = null;
for(int i = 0; i < n ; i++){
s[i]=sc.next();
a[i] = new BigDecimal(s[i]);
}
for(int i = 0; i < n-1; i++){
for(int j = 1; j < n; j++){
if(a[i].compareTo(a[j]) == -1){
BigDecimal temp = a[j];
a[j] = a[i];
a[i] = temp;
}
}
}
//Output
for(int i=0;i<n;i++){
s[i] = a[i].toString();
System.out.println(s[i]);
}
}
}
Sample Input:
9
-100
50
0
56.6
90
0.12
.12
02.34
000.000
Expected Output:
90
56.6
50
02.34
0.12
.12
0
000.000
-100

You can use the comparator to sort the BigDecimal
import java.math.BigDecimal;
import java.util.*;
class Solution{
public static void main(String []args){
Scanner sc= new Scanner(System.in);
int n=sc.nextInt();
String []s=new String[n+2];
for(int i=0;i<n;i++){
s[i]=sc.next();
}
sc.close();
Arrays.sort(s, 0, n, new Comparator<Object>() {
public int compare(Object a1, Object a2) {
BigDecimal bigDec1 = new BigDecimal((String) a1);
BigDecimal bigDec2 = new BigDecimal((String) a2);
return bigDec2.compareTo(bigDec1);
}
});
//Output
for(int i=0;i<n;i++)
{
System.out.println(s[i]);
}
}

import java.math.BigDecimal;
import java.util.*;
class Solution{
public static void main(String []argh)
{
Scanner sc= new Scanner(System.in);
int n=sc.nextInt();
String []s=new String[n+2];
for(int i=0;i<n;i++)
{
s[i]=sc.next();
}
for(int i=0;i<n;i++)
{
BigDecimal max=new BigDecimal(s[i]);
int idx=i;
for(int j=i+1;j<n;j++)
{
BigDecimal curr=new BigDecimal(s[j]);
if(curr.compareTo(max)==1)
{
max=curr;
idx=j;
}
}
String temp=s[i];
s[i]=s[idx];
s[idx]=temp;
}
for(int i=0;i<n;i++)
{
System.out.println(s[i]);
}
}
}

Looks like you're throwing an NPE because you're trying to access a null array.
BigDecimal a[] = null; // <---- null array
for (int i = 0; i < n; i++) {
s[i] = sc.next();
a[i] = new BigDecimal(s[i]); // <---- accessing null array a
}
Try initializing your array with the n length used on input
BigDecimal a[] = new BigDecimal[n];
Edit
in response to Mariano's answer, your
if (a[i].compareTo(a[j]) == -1)
is correct, as is. See BigDecimal javadoc
Returns:
-1, 0, or 1 as this BigDecimal is numerically less than, equal to, or greater than val.

You have a couple of errors in your code.
First you are not initializing the a array, BigDecimal a[] = null should be replaced by BigDecimal a[] = new BigDecimal[n] to avoid the NullPointerException.
Finally you are implementing the sort algorithm wrong, you should replace the inner for (int j = 1; j < n; j++) with for (int j = i + 1; j < n; j++)
Here is how your code should look like:
import java.math.BigDecimal;
import java.util.Scanner;
public class Solution {
public static void main(final String[] argh) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
String[] s = new String[n];
BigDecimal a[] = new BigDecimal[n];
for (int i = 0; i < n; i++) {
s[i] = sc.next();
a[i] = new BigDecimal(s[i]);
}
for (int i = 0; i < n - 1; i++) {
for (int j = i + 1; j < n; j++) {
if (a[i].compareTo(a[j]) == -1) {
BigDecimal temp = a[j];
a[j] = a[i];
a[i] = temp;
}
}
}
// Output
for (int i = 0; i < n; i++) {
s[i] = a[i].toString();
System.out.println(s[i]);
}
}
}

Related

Sorting empty and word array in java

I want to write a code which can sort char array element. But the problem is where i want to sort 'a' before 'aa' element and I don't know how to write this part. It always sort 'aa' before 'a'. At first it get inputs from user and if we write '0' it will print sorted array.
import java.util.Scanner;
public class First {
public static void main(String[] args) {
int i, num = 0;
char[][] arr = new char[1000][1000];
char[] index = new char[1000];
Scanner myObj = new Scanner(System.in);
for(i = 0; i < 1000; i++){
arr[i] = myObj.next().toCharArray();
if(arr[i][0] == '0'){
break;
}
else{
num++;
}
for(int j = 0; j < i; j++){
if(arr[i][0] < arr[j][0]){
index = arr[i];
arr[i] = arr[j];
arr[j] = index;
j = 0;
}
}
}
for(i = 0; i < num; i++){
System.out.println(arr[i]);
}
}
}
You have to consider that 'aa' is not a char, instead 'a' is a char.
If you want to sort strings the code is nearly okay.
Here an example:
import java.util.Scanner;
public class First {
public static void main(String[] args) {
int num = 0;
String[] arr = new String[1000];
String index = "";
Scanner myObj = new Scanner(System.in);
for(int i = 0; i < 1000; i++){
arr[i] = myObj.nextLine();
if(arr[i].equals("0")){
break;
}
else{
num++;
}
for(int j = 0; j < i; j++){
if(arr[i].compareTo(arr[j]) < 0){
index = arr[i];
arr[i] = arr[j];
arr[j] = index;
j = 0;
}
}
}
System.out.print("[ ");
for(int i = 0; i < num; i++){
System.out.print(arr[i] + " ");
}
System.out.println("]");
}
}
Input:
aaaaaaaa
aaaaaaa
aaaaaa
aaaaa
aaaa
aaa
aa
a
0
Expected Output:
[ a aa aaa aaaa aaaaa aaaaaa aaaaaaa aaaaaaaa ]
It is only sorting by the first char of an entered word.
Thus it seems like the input-order is preserved.
Issue
Adding some debug-prints shows the comparison of first-char is leading to incorrect or unwanted aa before a case:
import java.util.Scanner;
public class First {
public static void main(String[] args) {
int i, num = 0;
char[][] arr = new char[1000][1000];
char[] index = new char[1000];
Scanner myObj = new Scanner(System.in);
for(i = 0; i < 1000; i++){
arr[i] = myObj.next().toCharArray();
if(arr[i][0] == '0'){
break;
}
else{
num++;
}
System.out.printf("Debug [%d]: '%s' \n", i, String.valueOf(arr[i]));
for(int j = 0; j < i; j++){
System.out.printf("Compare '%s' < '%s' = %s\n", arr[i][0], arr[j][0], (arr[i][0] < arr[j][0]));
if(arr[i][0] < arr[j][0]){
index = arr[i];
arr[i] = arr[j];
arr[j] = index;
j = 0;
}
}
}
for(i = 0; i < num; i++){
System.out.println(arr[i]);
}
}
}
Output:
a
Debug [0]: 'a'
aa
Debug [1]: 'aa'
Compare 'a' < 'a' = false
0
a
aa
Refactored and solved
I just added a bit output to interact with user.
Also refactored a bit (extract into methods, and control length of arrays with a configurable constant).
import java.util.Scanner;
public class First {
private static final int LENGTH = 10;
private static final Scanner myObj = new Scanner(System.in);
public static void main(String[] args) {
char[][] arr = new char[LENGTH][LENGTH];
System.out.println("Enter elements (each on a new line, 0 stops):");
int num = readArray(0, arr);
System.out.printf("Printing %d elements:\n", num);
printArray(num, arr);
}
private static int readArray(int num, char[][] arr) {
char[] index;
int i;
for (i = 0; i < LENGTH; i++) {
arr[i] = readChars();
if (arr[i][0] == '0') {
break;
} else {
num++;
}
for (int j = 0; j < i; j++) {
if (String.valueOf(arr[i]).compareTo(String.valueOf(arr[j])) < 0) { // entire array compared (chars in sequence) instead only: arr[i][0] < arr[j][0]
index = arr[i];
arr[i] = arr[j];
arr[j] = index;
j = 0;
}
}
}
return num;
}
private static void printArray(int num, char[][] arr) {
int i;
for (i = 0; i < num; i++) {
System.out.println(arr[i]);
}
}
private static char[] readChars() {
return myObj.next().toCharArray();
}
}
Output is as expected (a before aa):
Enter elements (each on a new line, 0 stops):
z
aa
b
a
0
Printing 4 elements:
a
aa
b
z
How it works
Entire array compared (chars in sequence) instead only the first char of each array.
before:
arr[i][0] < arr[j][0]
after:
String.valueOf(arr[i]).compareTo(String.valueOf(arr[j])) < 0
Bonus Tip: Naming can help to spot logical bugs
When renaming the methods and variable names it may get a bit clearer what the program does, we call it semantics:
myObj becomes scanner
i becomes index or wordIndex or lineIndex and lastLineIndex
j is actually a character-index ... but in this short scope it should can be self-evident
char-arrays can be lines or words
num becomes length of lines or countLines
and all the method-names are adjusted in semantics to operate on lines, expressed by name <verb>Lines
import java.util.Scanner;
public class First {
private static final int LENGTH = 10;
private static final Scanner scanner = new Scanner(System.in);
public static void main(String[] args) {
char[][] lines = new char[LENGTH][LENGTH];
System.out.println("Enter elements (each on a new line, 0 stops):");
int countLines = readLines(lines);
System.out.printf("Printing %d elements:\n", countLines);
printLines(lines, countLines);
}
private static int readLines(char[][] lines) {
int linesRead = 0;
for (int lineIndex = 0; lineIndex < LENGTH; lineIndex++) {
lines[lineIndex] = readLine();
if (lines[lineIndex][0] == '0') {
break;
} else {
linesRead++;
}
sortLines(lines, lineIndex);
}
return linesRead;
}
private static void sortLines(char[][] lines, int lastLineIndex) {
for (int j = 0; j < lastLineIndex; j++) {
if (String.valueOf(lines[lastLineIndex]).compareTo(String.valueOf(lines[j])) < 0) { // entire array compared (chars in sequence) instead only: arr[i][0] < arr[j][0]
char[] line = lines[lastLineIndex];
lines[lastLineIndex] = lines[j];
lines[j] = line;
j = 0;
}
}
}
private static void printLines(char[][] lines, int length) {
for (int i = 0; i < length; i++) {
System.out.println(lines[i]);
}
}
private static char[] readLine() {
return scanner.next().toCharArray();
}
}

not able to sort array by ascending order

I have just started to do programming ...I am trying to sort an array in ascending order.. but not getting desired result , please point where i am doing wrong..
public static void main(String[] args) {
int count, temp;
// User inputs the array size
Scanner scan = new Scanner(System.in);
System.out.print("Enter number of elements you want in the array: ");
count = scan.nextInt();
int num[] = new int[count];
System.out.println("Enter array elements:");
for (int i = 0; i < count; i++) {
num[i] = scan.nextInt();
}
scan.close();
{
int i = 0;
while (i <= count) {
for (int j = i + 1; j < count; j++) {
if (num[i] > num[j]) {
temp = num[i];
num[i] = num[j];
num[j] = temp;
i++;
}
}
}
}
System.out.print("Array Elements in Ascending Order: ");
for (int i = 0; i < count - 1; i++) {
System.out.print(num[i] + ", ");
}
System.out.print(num[count - 1]);
}
you should increment the i outside the for loop or you can get rid of the while loop and use for loop too, you can find the code below :
import java.util.Scanner;
public class Ascending _Order
{
public static void main(String[] args)
{
int n, temp;
Scanner s = new Scanner(System.in);
System.out.print("Enter no. of elements you want in array:");
n = s.nextInt();
int a[] = new int[n];
System.out.println("Enter all the elements:");
for (int i = 0; i < n; i++)
{
a[i] = s.nextInt();
}
for (int i = 0; i < n; i++)
{
for (int j = i + 1; j < n; j++)
{
if (a[i] > a[j])
{
temp = a[i];
a[i] = a[j];
a[j] = temp;
}
}
}
System.out.print("Ascending Order:");
for (int i = 0; i < n - 1; i++)
{
System.out.print(a[i] + ",");
}
System.out.print(a[n - 1]);
}
}
Output:
Enter no. of elements you want in array:5
Enter all the elements: 4 3 2 6 1
Ascending Order:1,2,3,4,6
or you can use the method sort :
import java.util.Scanner;
import java.util.Arrays;
public class Ascending_Order {
public static void main(String[] args) {
int n, temp;
Scanner s = new Scanner(System.in);
System.out.print("Enter no. of elements you want in array:");
n = s.nextInt();
int a[] = new int[n];
System.out.println("Enter all the elements:");
for (int i = 0; i < n; i++) {
a[i] = s.nextInt();
}
Arrays.sort(a);
System.out.print("Ascending Order:");
for (int i = 0; i < n - 1; i++) {
System.out.print(a[i] + ",");
}
System.out.print(a[n - 1]);
}
}
Output:
Enter no. of elements you want in array:5
Enter all the elements: 4 3 2 6 1
Ascending Order:1,2,3,4,6

PROGRAM to find least common entry in array

I was writing the code for the least occurring element in the array and for some reason my logic goes wrong and the compiler just prints either the first or the second element in the array? anyone know what's wrong?
package javaapplication10;
import java.util.*;
public class JavaApplication10 {
public static void main(String[] args) {
int m =1000;
int count = 0;
int store = 0;
int c = 0;
Scanner scan = new Scanner(System.in);
int[] a = new int[20] ;
int n;
System.out.print("Enter no of elements");
n = scan.nextInt();
for(int i =0; i<n;i++) {
a[i] = scan.nextInt();
}
for(int i =0; i <n ; i++) {
c = a[i] ;
for(int j =0; j <n ; j++) {
if(a[j] ==c) {
count++ ;
}
if(j == (n-1)) {
if(count<m ) {
store = a[i];
m = count;
}
}
count = 0;
}
}
System.out.print(store);
}
}
A better solution is to do sorting. We first sort the array, then linearly traverse the array.
static int leastFrequent(int arr[], int n)
// n is length of array
{
// Sort the array
Arrays.sort(arr);
// find the min frequency using
// linear traversal
int min_count = n+1, res = -1;
int curr_count = 1;
for (int i = 1; i < n; i++) {
if (arr[i] == arr[i - 1])
curr_count++;
else {
if (curr_count < min_count) {
min_count = curr_count;
res = arr[i - 1];
}
curr_count = 1;
}
}
// If last element is least frequent
if (curr_count < min_count)
{
min_count = curr_count;
res = arr[n - 1];
}
return res;
}
I guess you are trying to implement the following logic
Find the count of each element in the array
If you find an element with lower count - store the element
Repeat for each element in the array - to find the lowest element.
You should have rest the count at the end of the inner loop as,
package javaapplication10;
import java.util.*;
public class JavaApplication10 {
public static void main(String[] args) {
int m =1000;
int count = 0;
int store = 0;
int c = 0;
Scanner scan = new Scanner(System.in);
int[] a = new int[20] ;
int n;
System.out.print("Enter no of elements");
n = scan.nextInt();
for(int i =0; i<n;i++) {
a[i] = scan.nextInt();
}
for(int i =0; i <n ; i++) {
c = a[i] ;
for(int j =0; j <n ; j++) {
if(a[j] ==c) {
count++ ;
}
if(j == (n-1)) {
if(count<m ) {
store = a[i];
m = count;
}
}
}
count = 0;
}
System.out.print(store);
}
}
You have a single counter, so you'll lose this counting once you transition from one element to another.
You could hold an auxiliary map of counters and update it as you go, but frankly, using Java's streams will save you a lot of boilerplate code:
int leastOccuring =
Arrays.stream(a)
.boxed()
.collect(Collectors.groupingBy(Function.identity(), Collectors.counting())
.entrySet()
.stream()
.min(Map.Entry.comparingByValue())
.map(Map.Entry::geyKey)
.get();
This would be the correct code for your program.
import java.util.*;
public class LeastOccuringElementInArray {
public static void main(String[] args) {
int m = 0;
int count = 0;
int store = 0;
int c = 0;
Scanner scan = new Scanner(System.in);
int[] a = new int[20] ;
int n;
System.out.print("Enter no of elements");
n = scan.nextInt();
for(int i =0; i<n;i++)
{
a[i] = scan.nextInt();
}
for(int i =0; i <n ; i++)
{ c = a[i] ;
for(int j =0; j <n ; j++)
{
if(a[j] == c)
{
count++ ;
}
if(j == (n-1))
{
if(m!=0 && m > count)
{
store = a[i];
m = count;
}
else {
m = count;
}
}
}
count = 0;
}
System.out.print(store);
scan.close();
}
}

Difference between these two codes

What is the difference between these two codes?
1st code
import java.io.*;
import java.util.*;
import java.math.*;
public class Solution {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int arr[][] = new int[6][6];
int MAXsum = Integer.MIN_VALUE;
for(int i=0; i < 6; i++){
for(int j=0; j < 6; j++){
arr[i][j] = in.nextInt();
}
}
for(int i = 1;i<=4;i++)
{
int sum = 0;
for(int j = 1; j<=4;j++)
{
sum = arr[i][j] + arr[i-1][j-1] + arr[i-1][j] + arr[i-1][j+1] + arr[i+1][j-1] + arr[i+1][j] + arr[i+1][j+1];
if(sum > MAXsum)
MAXsum = sum;
}
}
System.out.println(MAXsum);
}
}
2nd code
import java.io.*;
import java.util.*;
import java.math.*;
public class Solution {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int arr[][] = new int[6][6];
int MAXsum = 0;
for(int i=0; i < 6; i++){
for(int j=0; j < 6; j++){
arr[i][j] = in.nextInt();
}
}
for(int i = 1;i<=4;i++)
{
int sum = 0;
for(int j = 1; j<=4;j++)
{
sum = arr[i][j] + arr[i-1][j-1] + arr[i-1][j] + arr[i-1][j+1] + arr[i+1][j-1] + arr[i+1][j] + arr[i+1][j+1];
if(sum > MAXsum)
MAXsum = sum;
}
}
System.out.println(MAXsum);
}
}
---> The only diff is in the MAXsum declaration then how both differ from each other?
Note:
The 1st code runs all test cases successfully and the second code does not run all test cases.
Integer.MIN_VALUE is the least possible number, which is Negative. In the test cases, the sum might be negative and 0 is greater than that. So 0 gets returned instead of the negative sum.

Given three integers a, b, and n,output the following series: a+20b,a+20b+21b,......,a+20b+21b+...+2n−1ba+20b,a+20b+21b,......,a+20b+21b+...+2n−1b

Constraints:
0≤t≤500
0≤a,b≤50
1≤n≤15
Sample Input:
2
0 2 10
5 3 5
Sample Output
2 6 14 30 62 126 254 510 1022 2046
8 14 26 50 98
This works in my IDE but when I try it in an online editor in hackerrank.com it throws an exception:
Exception in thread "main" java.util.NoSuchElementException: No line foundat
java.util.Scanner.nextLine(Scanner.java:1585)at
Solution.main(Solution.java:24)
Please explain why this happens.Thanks!
import java.io.*;
import java.util.*;
public class Solution {
public static void main(String[] args) {
int[] a = new int[10];
int[] b = new int[10];
int[] n = new int[10];
int t;
int sum;
StringBuilder sb =new StringBuilder();
Scanner iput = new Scanner(System.in);
t = Integer.parseInt(iput.nextLine());
if (t <= 500) {
for (int i = 0; i < t; i++) {
a[i] = Integer.parseInt(iput.next());
b[i] = Integer.parseInt(iput.next());
n[i] = Integer.parseInt(iput.next());
iput.nextLine();
}
} else
System.out.println("Enter value less than 500");
if (t <= 500) {
for (int i = 0; i < t; i++) {
if (a[i] <= 50 && b[i] <= 50 && n[i] <= 15 && n[i] != 0) {
for (int j=0;j<n[i];j++) {
sum = a[i];
for (int k = j;k >=0; k--) {
sum+=Math.pow(2,k)*b[i];
}
sb=sb.append(Integer.toString(sum)).append(" ");
}
System.out.println(sb);
sb.delete(0,sb.toString().length());
} else
System.out.println("Enter the values within the allowed limits");
}
}
}
}
Remove iput.nextLine(); on line 24 so that no extra reading will happen.
I think the below should work. Because value of T can be up to 500 So the array can be either int[] a = new int[t] or new int[500].
Note if you are using int[t] the get the value of t before defining a,b and n.
import java.io.*;
import java.util.*;
public class Solution {
public static void main(String[] args) {
int[] a = new int[500];
int[] b = new int[500];
int[] n = new int[500];
int t;
int sum;
StringBuilder sb =new StringBuilder();
Scanner iput = new Scanner(System.in);
t = Integer.parseInt(iput.nextLine());
if (t <= 500) {
for (int i = 0; i < t; i++) {
a[i] = Integer.parseInt(iput.next());
b[i] = Integer.parseInt(iput.next());
n[i] = Integer.parseInt(iput.next());
}
} else
System.out.println("Enter value less than 500");
if (t <= 500) {
for (int i = 0; i < t; i++) {
if (a[i] <= 50 && b[i] <= 50 && n[i] <= 15 && n[i] != 0) {
for (int j=0;j<n[i];j++) {
sum = a[i];
for (int k = j;k >=0; k--) {
sum+=Math.pow(2,k)*b[i];
}
sb=sb.append(Integer.toString(sum)).append(" ");
}
System.out.println(sb);
sb.delete(0,sb.toString().length());
} else
System.out.println("Enter the values within the allowed limits");
}
}
}
}
import java.util.Scanner;
public class hackerrank_loop {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int j = sc.nextInt();
for (int i = 0; i < j; i++) {
int a = sc.nextInt();
int b = sc.nextInt();
int n = sc.nextInt();
int x = 1;
int o = a;
for (int k = 0; k < n; k++) {
o = o + x * b;
System.out.print(o);
x = x << 1;
System.out.print(' ');
}
System.out.println();
}
}
}
I've solved in this way the problem.
For sure it can be done better.
Scanner in = new Scanner(System.in);
int q=in.nextInt();
int[][] app;
if(q<0 && q>500){
System.out.println("ERROR = Select a valid value o q");
}else{
app= new int[q][3];
for(int i=0;i<q;i++){
app[i][0] = in.nextInt();
app[i][1] = in.nextInt();
app[i][2]= in.nextInt();
}
for (int one=0;one<q;one++){
StringBuffer sb = new StringBuffer();
int a = app[one][0];
int b = app[one][1];
int n = app[one][2];
int sum = a;
for (int two=0; two < n; two++){
sum = sum + b*(int)Math.pow(2D,new Double(two));
sb.append(sum);
sb.append(" ");
}
System.out.println(sb);
}
}
in.close();

Categories