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) + ".");
}
}
}
}
Related
this is my first "problem": Make a program to allow the user to input an integer value to be searched in list3. Your program should display whether the inputted integer value is found in list3, how many of it is in list3, and what are their locations in list3?"
It's almost done, the only problem is that I couldn't follow what is written output given in the example:
List1 : 1 3 2 5 7 8 5 6 9 4
List2 : 2 1 4 3 2 1 4 2 0 2
List3 : 3 4 6 8 9 9 9 8 9 6
Input value to search in List3: 9
The value 9 is in List3!
There are 4 of it in List3.
Located at: list3[4], list3[5], list3[6], list3[8]
and this is my output:
list1 : 1 3 2 5 7 8 5 6 9 4
list2 : 2 1 4 3 2 1 4 2 0 2
list3 : 3 4 6 8 9 9 9 8 9 6
Input value to search in List3: 9
The value 9 is in List3!
There are 4 of it in List 3.
Located at: 4
how do i display the "located at: " like in the example?
EDITED
Sorry, I'm kinda new here and in Programming. This is my code:
import java.util.ArrayList;
import java.util.Scanner;
public class List2Sample
{
public static void main(String[] args)
{
int list1[] = new int[10];
int list2[] = new int[10];
int list3[] = new int[10];
String input = "";
int i, x, num = 0, count = 0;
boolean found = false;
ArrayList<Integer> arr = new ArrayList<Integer>(10);
Scanner in = new Scanner(System.in);
for(i = 0; i < 10; i++)
{
list1[i] = 0;
}
for(i = 0; i < 10; i++)
{
System.out.print("List 1 [" + i + "] : ");
try
{
list1[i] = in.nextInt();
}
catch(Exception e)
{
System.out.println("Error!");
}
}
for(i = 0; i < 10; i++)
{
list2[i] = 0;
}
for(i = 0; i < 10; i++)
{
System.out.print("List 2 [" + i + "] : ");
try
{
list2[i] = in.nextInt();
}
catch(Exception e)
{
System.out.println("Error!");
}
}
System.out.print("list1 : ");
for(i = 0; i < 10; i++)
{
System.out.print(list1[i] + "\t");
}
System.out.println();
System.out.print("list2 : ");
for(i = 0; i < 10; i++)
{
System.out.print(list2[i] + "\t");
}
System.out.println();
System.out.print("list3 : ");
for(i = 0; i < 10; i++)
{
list3[0] = list1[0] + list2[0]; list3[1] = list1[1] + list2[1]; list3[2] = list1[2] + list2[2];
list3[3] = list1[3] + list2[3]; list3[4] = list1[4] + list2[4]; list3[5] = list1[5] + list2[5];
list3[6] = list1[6] + list2[6]; list3[7] = list1[7] + list2[7]; list3[8] = list1[8] + list2[8];
list3[9] = list1[9] + list2[9];
System.out.print(list3[i] + "\t");
}
System.out.println();
System.out.print("Input value to search in List3: ");
x = in.nextInt();
arr.add(list3[0]);
arr.add(list3[1]);
arr.add(list3[2]);
arr.add(list3[3]);
arr.add(list3[4]);
arr.add(list3[5]);
arr.add(list3[6]);
arr.add(list3[7]);
arr.add(list3[8]);
arr.add(list3[9]);
for (int n : list3)
{
if (n == x)
{
found = true;
break;
}
}
for (i = 0; i < 10; i++)
{
if (list3[i] == x)
{
count++;
}
}
for (Integer value : arr)
{}
int pos = arr.indexOf(x);
if(found)
System.out.println("The value " + x + " is in List3!");
else
System.out.println("The value " + x + " is in List3!");
System.out.println("There are " + count + " of it in List 3.");
System.out.println("Located at: " + pos);
}
}
Assuming list3 is an list of integers then using java8 streams
String locations=IntStream.range(0,list3.size())
.filter(i->list3.get(i)==userInput)
.map(index->"list3["+index+"]")
.collect(Collectors.joining(","));
Int occurences=locations.split(","). length;
if(occurences>0){System.out.println(userInput +"occurred" + occurences +" Times +" at locations "+locations);}
else{System.out.println(userInput +"Was not found");}
indexOf(ch) will only return the first appearance of the value in the array, if you want, you could supplement a second parameter to tell Java where to start looking for the character, like this: indexOf(ch, fromIndex).
However, in your case, it's much easier to just use an index based loop to loop through all elements in the array, then record the positions if you found matching characters, like this:
for(int i = 0; i < arr.length; i++){ // loop through all indices of the array, starting from 0, end at arr.length - 1
if(arr[i] == ch){ // arr[i] is each character in the array at index i, ch is the target character you're matching against
System.out.println("Character found at position " + i);
}
}
If the user searches a number within the array, the system should spit out the index that the number is located. If the number is not in the array, then the system should print out "X was not found." Why will these two IF statements not do the trick?
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int[] array = new int[10];
array[0] = 6;
array[1] = 2;
array[2] = 8;
array[3] = 1;
array[4] = 3;
array[5] = 0;
array[6] = 9;
array[7] = 7;
System.out.print("Search for?");
int searching = Integer.valueOf(scanner.nextLine());
for (int i = 0; i < array.length; i++) {
if (searching == array[i]) {
System.out.println(searching + " is at index " + i);
} if (searching!= array[1]) {
System.out.println(searching +" was not found.");
break;
}
}
// Implement the search functionality here
}
}
Check the length as well in the second if condition.
Also you have to break when the number is found.
please see below code for reference.
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int[] array = new int[10];
array[0] = 6;
array[1] = 2;
array[2] = 8;
array[3] = 1;
array[4] = 3;
array[5] = 0;
array[6] = 9;
array[7] = 7;
System.out.print("Search for?");
int searching = Integer.valueOf(scanner.nextLine());
for (int i = 0; i < array.length; i++) {
if (searching == array[i]) {
System.out.println(searching + " is at index " + i);
break;
}
if (searching != array[i] && i == (array.length - 1)) {
System.out.println(searching + " was not found.");
break;
}
}
// Implement the search functionality here
}
Your second if statement seems to always be checking index 1 of your array.
if (searching!= array[1]) {
System.out.println(searching +" was not found.");
break;
}
Additionally, checking for a value not being in the array should likely not occur within the for loop, but instead be assumed or tracked with a boolean if you reach the end of the for loop without finding a match.
if (searching!= array[1]) {
System.out.println(searching +" was not found.");
break;
}
This line doesn't makes sense because in the first iteration, it will check the first element of the array and if it doesn't match, it'll get out of the loop.
You can keep a track if the item was found by simply creating a boolean variable:
boolean found = false;
Then in your code:
for (int i = 0; i < array.length; i++) {
if (searching == array[i]) {
System.out.println(searching + " is at index " + i);
found = true;
break;
//When the search is done and we find the element, we make the found true
//to indicate the search is finished. And we get out from the loop by "break"
}
}
// If the above loop didn't get into the if statement, this will never be true,
// indicating that the number was not found in the array.
if(!found)
System.out.println(searching +" was not found.");
I guess you want to check if the searching value is part of the array and only want to print one final answer.
I modified your code a little bit to explain my answer:
removed break;
changed searching!= array[1] to searching!= array[i]
for (int i = 0; i < array.length; i++) {
if (searching == array[i]) {
System.out.println(searching + " is at index " + i);
}
if (searching!= array[i]) {
System.out.println(searching +" was not found.");
}
}
In this solution we print the result for every element of the array. You choosed an array with 10 elements. You set the values for the first 8 elments. The rest will be default initiliased with 0.
Assuming searching is 0. Iterating through the for-loop will result in the following prints:
First element 6 -> "0 was not found."
Second element 2 -> "0 was not found."
...
Sixth element 0 -> "0 is at index 5"
Seventh element 7 -> "0 was not found."
Eighth element 2 -> "0 was not found."
Ninth element 0 -> "0 is at index 8"
Tenth element -> "0 is at index 9"
If you want one answer you can modify the term like this
//Searching for the element
Integer index = null;
for (int i = 0; i < array.length; i++) {
if (searching == array[i]) {
index = i;
break; //quits the for-loop when the value searching is found
}
}
// Printing the result
if (index != null) {
System.out.println("First occurance of "+ searching + " at index " + i);
} else {
System.out.println(searching +" was not found.");
}
I wish you much fun while programming.
You need to use the debugger to get better understanding of the loop and conditions.
For example, what is the purpose of searching!= array[1] statement?
Is "else" missing in the following line } if (searching!= array[1]) {? And so forth...
You need to be more specific with the question in terms of: what behavior do you expect and what is the actual behavior of the code fragment.
Then you will get more help and explanations here on SO.
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++;
}
I have an addition program:
import java.io.*;
public class sum
{
int num;
int sum = 0;
int result;
public void findsum() throws IOException
{
BufferedReader Br = new BufferedReader(new InputStreamReader(System.in));
System.out.print("enter the value for N : ");
num = Integer.parseInt(Br.readLine());
int nums[] = new int[num+1];
for(int i = 1; i <= num; i++)
{
System.out.print("\n Enter " + i + " number: ");
nums[i]= Integer.parseInt(Br.readLine());
sum = sum + nums[i];
}
System.out.print("\n Sum is : " + sum );
}
public static void main(String args[]) throws IOException
{
sum sm = new sum();
sm.findsum();
}
}
Output:
It takes N Integer values as input from the user and returns sum of those N numbers.
But I want if any of the number is equal to the other one it will automatically ignore them in addition.
Just verify if the input number isn't in the array yet.
Change your for loop with this and it will work fine:
for (int i = 1; i <= num; i++) {
System.out.print("\n Enter the " + i + " number : ");
int x = Integer.parseInt(Br.readLine());
int j=0;
while(j<num && nums[j]!=x) {
j++;
}
if(j>=num) {
nums[i] = x;
}
sum = sum + nums[i];
}
From your question
i want if any of the number is equal to the other one it will
automatically ignore them in addition
It will easy if you use Set here
Set<Integer> numbers=new HashSet<>();
for(int i = 1;i<=num;i++){
System.out.print("\n Enter " + i + " number : ");
numbers.add(Integer.parseInt(Br.readLine())); // add to set
}
Now duplicate values not consider. Then simply add elements in the Set.
There are couple of issues:
Your for loop starts with 1 and the index of array that you used is nums[i] which means your array will start with 1. Array start with 0th index so used i-1 when you are referring index in for loop for your array or use loop starting from 0 till n-1.
If you want to stick with your implementation with Array then in every for loop, before doing the sum you need to iterate over each earlier element to check if element already exist in an array something like:
numberFound = false;
for (int j = 1; j < i; j++) {
if (nums[j - 1] == nums[i - 1]) {
numberFound = true;
System.out.println("Duplicate number " + nums[i - 1]
+ " will be ignored");
break;
}
}
if (!numberFound) {
sum = sum + nums[i - 1];
}
Use Set to remove redundancy
Set<Integer> num = new HashSet<Integer>();
num.add(123);
num.add(123);
num.add(1);
num.add(1);
Integer sum=0;
for(Object a: num.toArray()){
sum+=(Integer)a;
}
System.out.println(sum); //124
When using Java 8 you can let the Stream API do the work:
Stream#distinct()
From the JavaDoc:
Returns a stream consisting of the distinct elements (according to Object.equals(Object)) of this stream.
How to use:
final int[] nums = new int[] {1, 2, 2, 3, 4, 4, 4};
final int sum = IntStream.of(nums)
.distinct()
.sum();
System.out.println(sum); // prints 10 (1 + 2 + 3 + 4);
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.