I am attempting to find the occurrence frequency of a number in a sequence.
for example when sequence is :
1, 1, 3, 4
output should be
1 found 3 times
, 3 found 1 times
, 4 found 1 time
and so on. I have the following code
import java.util.*;
class fre {
public static void main(String a[]) {
int c = a.length;
int d[] = new int[c];
int num = 0;
for (int p = 0; p < c; p++)
d[p] = Integer.parseInt(a[p]);
for (int z : d)
System.out.println(z);
for (int i = 0; i < c - 1; i++) // FROM THIS LINE ERROR IS THROWN
{
for (int t = 0; t < c - 1; i++) {
if (d[i] == d[t]) {
num++;
}
}
System.out.println("the element" + i + "found" + num + "times");
}
}
}
ERROR : ARRAY OUT OF BOUND INDEX
Shouldn't
for (int t = 0; t < c - 1; i++)
be
for (int t = 0; t < c - 1; t++)
You are incrementing i again in the second loop.
Well, first of all, you increment i instead of t in the inner loop.
Changing this, the program seems to work.
Change the output line to sth. like
System.out.println("the element " + d[i] + " found " + num + " times");
To make it readable.
Not saying there is no better way to solve this...
ok
Benno
a is an array that holds all the command line parameters. You are using a.length which determines the amount of command line parameters given. I guess you probably want to pass the length of the array by a command line parameter instead. If I am correct, you should use something like int c = a[0]; to get the first command line parameter. Of course that is not good style without any checks, but if I get started on that I had to rewrite your whole code ;)
Your example is wrong.
Untested:
public static void main(String args[])
{
Map<Integer, Integer> result = new HashMap<>();
for (String s : args) {
Integer currentNumber = Integer.parseInt(s);
// don't forget error handling if s is not a number
Integer currentCount = result.get(currentNumber);
if (currentCount == null) { // you could also check with result.containsKey(..)
currentCount = 0;
}
result.put(currentNumber, currentCount + 1);
}
for (Map.Entry<Integer, Integer> entry : result) {
System.out.println("The element: " + entry.getKey() + " found " + entry.getValue() + " times");
}
}
This is probably slower than your version, but easier to understand.
Related
I am trying to make a counter with a list of 10 elements in random position, the problem is that after making the complete tour of my array I must print on the screen how many numbers that are repeated.
To do this, I made the method out of my Main space, I declared the array and the "for loop" to tour my array, the question is after that I must will include in the same method the counter ? ...
public static int Vectores(int a[]) {
// Declared variable
a = new int[10];
int lf = a.length;
// Here we will tour the array and then complete the arrays with random numbers.
for (int i = 0; i < lf; i++) {
a[i] = (int) (Math.random() * 100);
System.out.println(" A:" + a[i] );
}
return a[i];
// Here will be an "if condition" + and for loop to the counter
int counter = 0;
for (int i = 0; i < 10; i++) {
}
} // END
Your method is taking an array as param, which is being assigned with a new array and the array itself not return. If the random values have to be generated in the method and only the number of repetitions needed, the parameter is not needed! And you also have a return statement after your first loop, making the rest of the code unreachable!
This being said, you could track the repetitions as follow:
...
int a[] = new int[10];
Map<Integer, Integer> count = new HashMap<>();
for (int i = 0; i < a.length; i++) {
a[i] = (int) (Math.random() * 10);
count.compute(a[i], (k, ov) -> ov != null ? ++ov : 1);
}
List<Entry<Integer, Integer>> repetitions = count.entrySet().stream()
.filter(e -> e.getValue() > 1)
.collect(Collectors.toList());
// Return the value & or display the details
if (repetitions.isEmpty()) {
System.out.println("No repetition found !");
} else {
System.out.println("Number of value which are repeated : " + repetitions.size());
repetitions.forEach(e -> System.out.println(e.getKey() + " -> " + e.getValue() + " times"));
}
...
Cheers!
so this a part of my code containing my LinkedList. How can I find the match in my set of numbers.
LinkedList <Integer> mylist = new LinkedList<> ();
for(int i : 1; i<=5; i++){
System.out.println("Process " + i + has :);
int numINPUT = scan.nextint();
mylist.add(numINPUT);
}
My desired output is:
Process 1 has : 3
Process 2 has : 4
Process 3 has : 1
Process 4 has : 5
Process 5 has : 2
Matched : Process 1 and Process 3.
A brute force thing could look like this:
for (int i=0; i<mylist.size(); i++) {
int pointingToIndex = mylist.get(i);
if (pointingToIndex > 0 && pointingToIndex < mylist.size) {
int pointedTo = mylist.get(pointingToIndex);
if (pointedTo == i) {
System.out.println("match for index: " + i + " and " + pointingToIndex);
}
}
}
you simply iterate your list; and for each index you check if the value on that index is another valid index
if so, you fetch the value for that other index, and then you check for a match
you might need some additional "marker" to avoid printing duplicates (I think my solution will print 1-3, and then 3-1 later on)
and yes, this is not exactly printing what you ask for - but should give you enough to get going and finish your homework yourself
Besides: look into your naming. mylist says ... nothing. Why not call it numbers or maybe processIDs or something like that?
You just have to compare all pairs of list items. If an index of one item equals the value of another one and vice versa, you have a match. Keep in mind, that Java indices start with 0, your indices start with 1.
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
LinkedList <Integer> mylist = new LinkedList<> ();
for(int i = 1; i<=5; i++){
System.out.print("Process " + i + " has: ");
int numINPUT = scan.nextInt();
mylist.add(numINPUT);
}
for(int i = 0; i < mylist.size(); i++) {
for(int j = i + 1; j < mylist.size(); j++) {
int value1 = mylist.get(i);
int value2 = mylist.get(j);
if(value1 == (j + 1) && value2 == (i + 1)) {
System.out.println("Matched : Process " + (i + 1) + " and Process " + (j + 1) + ".");
}
}
}
}
How do I use the command printf to print my output the same way in the attached output file?
this is my code currently:
else if (args[0].equals("fib")) {
for (int i = 0; i < (Integer.parseInt(args[1]) + 1); ++i) {
System.out.println(getFib(i));
}
}
How do i change it to make it print like the attached picture?
Thank you guys for your help!
Here is an example.
Instead of instant printing add all numbers into a list:
List<Integer> numbers = new ArrayList<>();
for (int i = 1; i <= number; i++) {
numbers.add(fibonacci(i));
}
Then make a pattern for printf():
String pattern = "%" + (numbers.get(numbers.size()-1).toString().length() + 10) + "d";
where (numbers.get(numbers.size()-1).toString().length() + 10) is the sum of the number of characters in the largest number plus 10 spaces between columns.
Then print all elements of the list. The counter is needed in order to have no more than 6 columns:
int counter = 0;
for (Integer integer : numbers) {
if (counter == 6) {
System.out.println(" ");
counter = 0;
}
System.out.printf(pattern, integer);
counter++;
}
This is a challenge question from my online textbook I can only get the numbers to prin forward... :(
Write a for loop to print all elements in courseGrades, following each element with a space (including the last). Print forwards, then backwards. End each loop with a newline.
Ex: If courseGrades = {7, 9, 11, 10}, print:
7 9 11 10
10 11 9 7
Hint: Use two for loops. Second loop starts with i = NUM_VALS - 1.
Note: These activities may test code with different test values. This activity will perform two tests, the first with a 4-element array (int courseGrades[4]), the second with a 2-element array (int courseGrades[2]).
import java.util.Scanner;
public class CourseGradePrinter {
public static void main (String [] args) {
final int NUM_VALS = 4;
int[] courseGrades = new int[NUM_VALS];
int i = 0;
courseGrades[0] = 7;
courseGrades[1] = 9;
courseGrades[2] = 11;
courseGrades[3] = 10;
/* Your solution goes here */
for(i=0; i<NUM_VALS; i++){
System.out.print(courseGrades[i] + " ");
}
for(i=NUM_VALS -1; i>3; i++){
System.out.print(courseGrades[i]+ " ");
}
return;
}
}
This is the code to answer the question from zyBooks, 6.2.3: Printing array elements with a for loop.
for (i = 0; i < NUM_VALS; i++) {
System.out.print(courseGrades[i] + " ");
}
System.out.println("");
for (i = NUM_VALS - 1; i >= 0; i--) {
System.out.print(courseGrades[i] + " ");
}
System.out.println("");
Your two loops almost were correct. Try using this code:
for (int i=0; i < NUM_VALS; i++) {
// this if statement avoids printing a trailing space at the end.
if (i > 0) {
System.out.print(" ");
}
System.out.print(courseGrades[i]);
}
for (int i=NUM_VALS-1; i >= 0; i--) {
if (i > 0) {
System.out.print(" ");
}
System.out.print(courseGrades[i] + " ");
}
To print backwards you want:
for(i = NUM_VALS - 1; i >= 0; i--) {
System.out.print(courseGrades[i] + " ");
}
// To end with a newline
System.out.println("");
I also have been working on the this textbook question. The issue with the above code is that i has already been assigned, so trying using int in the for loop will cause an error. Below is the code I used to successfully achieve the desired outcome.
for ( i = 0 ; i <NUM_VALS; ++i) {
if (i > 0) {
System.out.print("");
}
System.out.print(courseGrades[i] + " ");
}
System.out.println("");
for ( i = NUM_VALS -1; i >=0; --i) {
if (i > 0) {
System.out.print("");
}
System.out.print( courseGrades[i] + " ");
}
System.out.println();
class CommandLineArgs {
public static void main(String args[]) {
int l = args.length;
int sum = 0;
for (int j = 0; j < l; j++) {
sum = Integer.parseInt(args[j]) + sum;
}
System.out.println("The Sum of All Elements entered at command line is : " + sum);
}
}
I tried using arguments but not able to do in using function as my required output is a=number1 and b=number2 and c=operator (+,-,/,*). Please help me in writing the program.
You need to use a case or if statement.
if(args[2].equalsIgnoreCase("+")
{
sum = Integer.parseInt(args[0]) + Integer.parseInt(args[1]);
}
else if(args[2].equalsIgnoreCase("*")
{
sum = Integer.parseInt(args[0]) * Integer.parseInt(args[1]);
}
etc...
you can use array for this
String[] arr= new String[l]; create a string array
for(int j=0;j<l ;j++){
arr[j] = args[j];// first of all store all inputs in the array
}
for(int i=0;i<arr.length;i++){
// then iterate over the array and check for the last char of array
if(arr[2].equalsIgnoreCase("+"){
sum = Integer.parseInt(arr[0]) + Integer.parseInt(arr[1]);
System.out.println("The Sum of All Elements entered at command line is : " + sum);
}else if(args[2].equalsIgnoreCase("*")
{
code for multiplication
}
}