patternjavaMinor
k_diff challenge in Java
Viewed 0 times
k_diffjavachallenge
Problem
Puzzle Description
Given \$N\$ numbers, \$N
-
2nd line contains \$N\$ numbers of the set. All the \$N\$ numbers are assured to be distinct.
Output Format:
Time limit is 5 seconds.
First I've tried using
But to achieve the puzzle description I couldn't see any better logic than this:
`import java.util.Scanner;
public class k_diff {
public int process() {
Scanner scanner = new Scanner(System.in);
int total_nums = scanner.nextInt();
int diff = scanner.nextInt();
int ary_nums[] = new int[total_nums];
for (int i = 0; i
Given \$N\$ numbers, \$N
-
2nd line contains \$N\$ numbers of the set. All the \$N\$ numbers are assured to be distinct.
Output Format:
- One integer saying the number of pairs of numbers that have a difference \$K\$.
Time limit is 5 seconds.
Sample Input : 5 2
1 5 3 4 2
Sample Output: 3
First I've tried using
ArrayLists and later tried using arrays. The code is bad and does not at all follow normal conventions of Java. But I'm not looking at that because execution time doesn't depend on it, right?But to achieve the puzzle description I couldn't see any better logic than this:
`import java.util.Scanner;
public class k_diff {
public int process() {
Scanner scanner = new Scanner(System.in);
int total_nums = scanner.nextInt();
int diff = scanner.nextInt();
int ary_nums[] = new int[total_nums];
for (int i = 0; i
Solution
Some things which just jump into my eyes (even if not asked, I'll tell you anyway):
- Whitespaces: Use whitespaces were appropriate, f.e.
for(int i=0;i
- Meaningful names: Name your variables after what they are, not what type they are. This especially includes simple for
loops. It might be taught or standard to usei, but I consider it bad practice because you never know what exactlyiis at first glance. Give your variables meaningful names, please, they deserve love too! Same goes for your classes.
- Split up where appropriate: if you've got only one function (main`) you're most likely doing something wrong. Split it into Input, Processing and Output.
Context
StackExchange Code Review Q#7316, answer score: 4
Revisions (0)
No revisions yet.