The code is supposed to output sorted array, yet it outputs zeros.
As an example, when running the program, write "2" when it asks for method, then "5", when it asks for count and "10" "9" "2" "5" "0", when it's asking for items. Then you'll see. I followed all the instructions given and I can't seem to find the problem with code, which changes inputted numbers to zeros, when outputting...
public static void secondMethod(int[] a) {
long t1 = System.nanoTime();
int N = a.length;
int b[] = new int[N];
int c[] = new int[N];
int[] tmp;
int len = 1;
for (int i = 0; i < a.length; i++) {
a[i] = b[i];
}
while (len < N) {
int n = 0;
int i;
int j;
int ri;
int rj;
for (int k=0; k<b.length; k+=2*len){{
n=k;
i = k;
j = k+len;
if(k+len<N){
ri = k+len;
}else{
ri = N;
}
if(k+2*len<N){
rj = k+2*len;
}else{
rj = N;
}
}
while(i<ri && j<rj){
if(b[i]<b[j]){
c[n]=b[i];
i++;
n++;
}else{
c[n]=b[j];
j++;
n++;
}
}
while(i<ri){
c[n]=b[i];
i++;
n++;
}
while(j<rj){
c[n]=b[j];
j++;
n++;
}
}
len = len*2;
tmp = b;
b = c;
c = tmp;
}
for (int i = 0; i < a.length; i++) {
a[i] = b[i];
}
long t2 = System.nanoTime();
long t = t2 - t1;
System.out.println("t=" + t);
}
public static void main(String[] args) {
int nm, mtd;
Scanner sc = new Scanner(System.in);
System.out.print("method: ");
if (sc.hasNextInt())
mtd = sc.nextInt();
else {
System.out.println("input-output error");
sc.close();
return;
}
if (mtd != 1 && mtd != 2) {
System.out.println("input-output error");
sc.close();
return;
}
System.out.print("count: ");
if (sc.hasNextInt())
nm = sc.nextInt();
else {
System.out.println("input-output error");
sc.close();
return;
}
int a[] = new int[nm];
System.out.println("items: ");
for (int i = 0; i < a.length; i++) {
if (sc.hasNextInt())
a[i] = sc.nextInt();
else {
System.out.println("input-output error");
sc.close();
return;
}
}
sc.close();
if (mtd == 1) {
firstMethod(a);
System.out.println("sorted: ");
for (int i = 0; i < a.length; i++)
System.out.print(a[i] + " ");
}
if (mtd == 2){
secondMethod(a);
System.out.println("sorted: ");
for (int i = 0; i < a.length; i++)
System.out.print(a[i] + " ");
}
}
In your code, in the secondMethod(int[] a) method, in the first for loop, use
b[i] = a[i];
instead of
a[i] = b[i];
and it should work.
Try debugging next time, it helps.
Related
I have a java code to read the length of an integer array, output the range, length of the gap, and any distinct elements inside. Additionally, it will output the numbers again with none repeated.
I would like to shorten the length of my main method.
My code produces the correct output, it is just very lengthy. Additionally, is there a way I can edit this main method to where it won't require a drastic change to my other methods? Thank you so much!
package ArrayPrograms;
import java.util.Scanner;
public class WIP{
static int LargestGap(int [] a, int n)
{
int diff = Math.abs(a[1] - a[0]);
for(int i = 1; i < a.length-1; i++)
if(Math.abs(a[i+1]-a[i]) > diff)
diff = Math.abs(a[i+1] - a[i]);
return diff;
}
int range(int a[], int n)
{
int max1 = Integer.MIN_VALUE;
for (int i = 0; i < n; i++)
{
for (int j = 0; j < n; j++)
{
if (Math.abs(a[i] - a[j]) > max1)
{
max1 = Math.abs(a[i] - a[j]);
}
}
}
return max1;
}
int numberOfDistinctElement(int a[], int n)
{
int num = 1;
for (int i = 1; i < n; i++)
{
int j = 0;
for (j = 0; j < i; j++)
if (a[i] == a[j])
break;
if (i == j)
num++;
}
return num;
}
int[] distinctElements(int a[], int n,int numberofDistinct)
{
int index = 0;
int[] distinct= new int[numberofDistinct];
for (int i = 0; i < n; i++)
{
int flag = 0;
for (int j = 0; j < i; j++){
if (a[i] == a[j]){
flag = 1;
break;
}
}
if (flag == 0){
distinct[index] = a[i];
index++;
}
}
return distinct;
}
***public static void main(String[] args)
{
Scanner in = new Scanner(System.in);
int num;
WIP obj=new WIP();
System.out.print("Enter the length of the array:");
num = in.nextInt();
int array[] = new int[num];
System.out.print("Enter the elements of the array: ");
for(int i = 0; i < num; i++)
{
array[i] = in.nextInt();
}
System.out.println("The largest gap in the array is "+WIP.LargestGap(array,num)+".");
System.out.println("The range of the array is "+obj.range(array,num)+".");
int numberofDistinct=obj.numberOfDistinctElement(array,num);
System.out.println("The number of distinct elements is "+numberofDistinct+".");
int[] distinctArray=obj.distinctElements(array,num,numberofDistinct);
System.out.print("The array of distinct elements is [");
for (int i = 0; i < distinctArray.length; i++)
if(i== distinctArray.length-1)
{
System.out.print(distinctArray[i]+"]");
}
else {
System.out.print( distinctArray[i]+ ",");
}
in.close();
}
}***
Sure thing. Here you go:
package arrayprograms;
import java.util.Scanner;
public class WIP{
static int LargestGap(int [] a, int n)
{
int diff = Math.abs(a[1] - a[0]);
for(int i = 1; i < a.length-1; i++)
if(Math.abs(a[i+1]-a[i]) > diff)
diff = Math.abs(a[i+1] - a[i]);
return diff;
}
int range(int a[], int n)
{
int max1 = Integer.MIN_VALUE;
for (int i = 0; i < n; i++)
{
for (int j = 0; j < n; j++)
{
if (Math.abs(a[i] - a[j]) > max1)
{
max1 = Math.abs(a[i] - a[j]);
}
}
}
return max1;
}
int numberOfDistinctElement(int a[], int n)
{
int num = 1;
for (int i = 1; i < n; i++)
{
int j = 0;
for (j = 0; j < i; j++)
if (a[i] == a[j])
break;
if (i == j)
num++;
}
return num;
}
int[] distinctElements(int a[], int n,int numberofDistinct)
{
int index = 0;
int[] distinct= new int[numberofDistinct];
for (int i = 0; i < n; i++)
{
int flag = 0;
for (int j = 0; j < i; j++){
if (a[i] == a[j]){
flag = 1;
break;
}
}
if (flag == 0){
distinct[index] = a[i];
index++;
}
}
return distinct;
}
static void showResults(int[] array, int num, WIP obj){
System.out.println("The largest gap in the array is "+WIP.LargestGap(array,num)+".");
System.out.println("The range of the array is "+obj.range(array,num)+".");
int numberofDistinct=obj.numberOfDistinctElement(array,num);
System.out.println("The number of distinct elements is "+numberofDistinct+".");
int[] distinctArray=obj.distinctElements(array,num,numberofDistinct);
System.out.print("The array of distinct elements is [");
for (int i = 0; i < distinctArray.length; i++)
if(i== distinctArray.length-1)
{
System.out.print(distinctArray[i]+"]");
}
else {
System.out.print( distinctArray[i]+ ",");
}
}
public static void main(String[] args)
{
Scanner in = new Scanner(System.in);
int num;
WIP obj=new WIP();
System.out.print("Enter the length of the array:");
num = in.nextInt();
int array[] = new int[num];
System.out.print("Enter the elements of the array: ");
for(int i = 0; i < num; i++)
{
array[i] = in.nextInt();
}
in.close();
showResults(array, num, obj );
}
}
There's not a whole lot you can do, like most of the comments say, but you can remove and edit some of the braces around that aren't necessary for the bodies. Here is a rough draft of it. The only things you could change besides that is to store all of the WIP.tests in variables in one code block and then print them all out in another code block; which would improve readability.
public static void main(String[] args)
{
Scanner in = new Scanner(System.in);
WIP obj = new WIP();
System.out.print("Enter the length of the array:");
int num = in.nextInt();
int array[] = new int[num] ;
System.out.print("Enter the elements of the array: ");
for(int i = 0; i < num; i++)
array[i] = in.nextInt();
System.out.println("The largest gap in the array is " + WIP.LargestGap(array,num) + ".");
System.out.println("The range of the array is " + obj.range(array,num) + ".");
int numberofDistinct = obj.numberOfDistinctElement( array, num );
System.out.println("The number of distinct elements is "+numberofDistinct+".");
int[] distinctArray = obj.distinctElements(array,num,numberofDistinct);
System.out.print("The array of distinct elements is [");
for (int i = 0; i < distinctArray.length; i++)
if(i== distinctArray.length-1)
System.out.print(distinctArray[i]+"]");
else
System.out.print( distinctArray[i]+ ",");
in.close();
}
import java.util.*;
public class Combination {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter a number : ");
String input = sc.next();
System.out.printf("You entered: %d\n", Integer.parseInt(input));
sc.close();
int[] arr = new int[100];
for (int i = 0; i < arr.length; i++) {
arr[i] = i + 1;
}
for (int i = 0; i <= 97; i++) {
int num_i = arr[i];
for (int j = i + 1; j <= 98; j++) {
int num_j = arr[j];
for (int k = j + 1; k <= 99; k++) {
int num_k = arr[k];
if (num_i + num_j + num_k == Integer.parseInt(input))
System.out.printf("(%d, %d, %d)", num_i, num_j, num_k);
}
}
}
}
}
When I get a number input, I want to make a code that represents this number as the sum of three numbers.
The code is complete, but there are several combinations. I want to print out only one combination. How can I edit it?
First, some important suggestions:
Do not parse input inside the nested loop as it will hit the performance. Do it once outside the nested loops.
Do not close Sacnner for System.in as it also closes System.in and there is no way to open it again without restarting JVM. It means that if it is being used in some other part of your application, your application will crash.
Always follow Java naming conventions e.g. you could name numJ instead of num_j.
Coming back to your problem, there are many ways to solve it and I have listed below just a couple of them:
Use break <<label>> to exit the nested loops:
import java.util.Scanner;
public class Combination {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter a number : ");
String input = sc.next();
System.out.printf("You entered: %d\n", Integer.parseInt(input));
int num = Integer.parseInt(input);
int[] arr = new int[100];
for (int i = 0; i < arr.length; i++) {
arr[i] = i + 1;
}
start: for (int i = 0; i <= 97; i++) {
int numI = arr[i];
for (int j = i + 1; j <= 98; j++) {
int numJ = arr[j];
for (int k = j + 1; k <= 99; k++) {
int numK = arr[k];
if (numI + numJ + numK == num) {
System.out.printf("(%d, %d, %d)", numI, numJ, numK);
break start;
}
}
}
}
}
}
A sample run:
Enter a number : 123
You entered: 123
(1, 22, 100)
Put the logic in a method and return:
import java.util.Scanner;
public class Combination {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter a number : ");
String input = sc.next();
System.out.printf("You entered: %d\n", Integer.parseInt(input));
int num = Integer.parseInt(input);
printFirstCombination(num);
}
static void printFirstCombination(int num) {
int[] arr = new int[100];
for (int i = 0; i < arr.length; i++) {
arr[i] = i + 1;
}
for (int i = 0; i <= 97; i++) {
int numI = arr[i];
for (int j = i + 1; j <= 98; j++) {
int numJ = arr[j];
for (int k = j + 1; k <= 99; k++) {
int numK = arr[k];
if (numI + numJ + numK == num) {
System.out.printf("(%d, %d, %d)", numI, numJ, numK);
return;
}
}
}
}
}
}
You can create a seperate function for that and after you find a combination, print it and return there and then to the main function. In case you didn't find a combination you return 1 which can be handled in the main function,
public class Combination {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter a number : ");
String input = sc.next();
System.out.printf("You entered: %d\n", Integer.parseInt(input));
int res = printCombination(input);
if(res == 1) {
// Do something
}
sc.close();
}
private static int printCombination(String input) {
int[] arr = new int[100];
for (int i = 0; i < arr.length; i++) {
arr[i] = i + 1;
}
for (int i = 0; i <= 97; i++) {
int num_i = arr[i];
for (int j = i + 1; j <= 98; j++) {
int num_j = arr[j];
for (int k = j + 1; k <= 99; k++) {
int num_k = arr[k];
if (num_i + num_j + num_k == Integer.parseInt(input)) {
System.out.printf("(%d, %d, %d)", num_i, num_j, num_k);
return 0;
}
}
}
}
return 1;
}
}
This question already has answers here:
How do I create a file and write to it?
(35 answers)
Closed 4 years ago.
I'm writing code that prints you combination of numbers from 1 to n. In console it works perfectly fine, but i need to print it into file.
What should i do?
Code:
public class Permutace {
public static void main(String args[]){
Scanner sc = new Scanner(System.in);
System.out.println("your number: ");
int N = sc.nextInt();
int[] sequence = new int[N];
for (int i = 0; i < N; i++) {
sequence[i] = i + 1;
}
permute(sequence, 0);
}
public static void permute(int[] a, int k){
if (k == a.length) {
for (int i = 0; i < a.length; i++) {
System.out.print(a[i]);
}
System.out.println();
} else {
for (int i = k; i < a.length; i++) {
int temp = a[k];
a[k] = a[i];
a[i] = temp;
permute(a, k + 1);
temp = a[k];
a[k] = a[i];
a[i] = temp;
}
}
}
}
public static void main(String args[]){
Scanner sc = new Scanner(System.in);
System.out.println("your number: ");
int N = sc.nextInt();
int[] sequence = new int[N];
PrintWriter writer = new PrintWriter("the-file-name.txt", "UTF-8");
for (int i = 0; i < N; i++) {
sequence[i] = i + 1;
}
permute(sequence, 0);
writer.close();
}
public static void permute(int[] a, int k){
if (k == a.length) {
for (int i = 0; i < a.length; i++) {
writer.println(a[i]);
}
writer.println();
} else {
for (int i = k; i < a.length; i++) {
int temp = a[k];
a[k] = a[i];
a[i] = temp;
permute(a, k + 1);
temp = a[k];
a[k] = a[i];
a[i] = temp;
}
}
}
I have tried the other questions like this but none seem to match it. I want it to repeat if the user enters Y after the numbers are sorted in the console.
Here is the code:
package compsorter;
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("In Ascending Order:");
for (int i = 0; i < n - 1; i++)
{
System.out.print(a[i] + ",");
}
System.out.print(a[n - 1]);
s.close();
}
}
Thanks!
Like this,
do{
//code here
//take input from user 'Y' or 'N'
}while(condition);
try do while for this reason.here is example of that : link
You can put
do { after
Scanner s = new Scanner(System.in);
and
} while(s.readLine().equals("Y"))
before
s.close();
You can do it with while loop.
Below is main method program you should have.
public static void main(String[] args) {
String flag = "Y";
Scanner s = new Scanner(System.in);
while (true) {
if ("Y".equalsIgnoreCase(flag)) {
int n, temp;
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("In Ascending Order:");
for (int i = 0; i < n - 1; i++) {
System.out.print(a[i] + ",");
}
System.out.print(a[n - 1]);
System.out.println();
System.out.print("Do you want to continue Y/N?");
flag = s.next();
} else {
break;
}
}
s.close();
}
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();