I'm trying to find the majority element using Boyer and Moore approach. The program should ask the user to input "n" number of lines on the first line, then there will be "n" numbers followed "n" lines as input. (Ex: user input 5 on the first line, then there will be 5 numbers followed)
Next, use Boyer and Moore approach to find the majority element of an input array. If the majority element doesn't exist in the input array, then execute -1. My program output shows 0 no matter what input I entered. Would you please check it and correct my program?
Output example:
4
12
12
1
12
12
/Or: 3 11 2 13 -1
public static void main (String[]args)
{
int a[] = new int [1000000];
Scanner sc = new Scanner (System.in);
// User input n number of lines
int numberOfLine = sc.nextInt();
//Loop to have n elements as input
for (int i = 1; i<= numberOfLine; i++)
{
a[i] = sc.nextInt();
}
// Call method to display majority element
getMajorityElement(a);
sc.close();
}
//Method to Find M.E using Boyer & Moore approach
public static void getMajorityElement(int [] array)
{
int majorityElement = array[0];
int count = 1;
for (int index = 1; index<array.length; index++)
{
if(majorityElement==array[index])
{
count++;
}
else if(count==0)
{
majorityElement = array[index];
count = 1;
}
else
{
count --;
}
}
// Check if candidate M.E occur more than n/2 times
count = 0;
for (int index = 0; index<array.length; index++)
{
if(array[index]==majorityElement)
{
count++;
}
}
if (count > array.length/2)
{
System.out.println(majorityElement);
}
else
{
System.out.println("-1");
}
}
The reason you get this behavior is that your array of 1,000,000 elements has a majority element of zero: only the initial three or four items are set, while the rest of the items are occupied by zeros - the default value of an int in Java.
Fix this problem by allocating at size once the length is entered. You also need to fix the code that reads input to make sure that the data ends up at indexes 0..numberOfLine-1:
Scanner sc = new Scanner (System.in);
// User input n number of lines
int numberOfLine = sc.nextInt();
int a[] = new int [numberOfLine];
//Loop to have n elements as input
for (int i = 0 ; i < numberOfLine ; i++) {
a[i] = sc.nextInt();
}
I'm supposed to write a program using for loops that print out the even indexes of my array. For example, if I create an array that has 10 numbers, it will have indexes from 0-9 so in that case I would print out the numbers at index 2, 4, 6 and 8. This is what I wrote so far but it doesn't work. Please note that I am not trying to print out the even numbers of the array. All I want are the even indexes.
Example I enter the following array: 3,7,5,5,5,7,7,9,9,3
Program output:
5 // (the number at index 2)
5 // (the number at index 4)
7 // (the number at index 6)
9 // (the number at index 8)
My Code:
public class Arrayevenindex
{
public static void main(String[] args)
{
int number; // variable that will represent how many elements the user wants the array to have
Scanner key = new Scanner(System.in);
System.out.println(" How many elements would you like your array to have");
number = key.nextInt();
int [] array = new int [number];
// let the user enter the values of the array.
for (int index = 0; index < number; index ++)
{
System.out.print(" Value" + (index+1) + " :");
array[index] = key.nextInt();
}
// Print out the even indexes
System.out.println("/nI am now going to print out the even indexes");
for (int index = 0; index < array.length; index ++)
{
if (array[number+1]%2==0)
System.out.print(array[number]);
}
}
}
You can just change your for loop and get rid of the inner IF...
for( int index = 0; index < array.length; index += 2) {
System.out.println(array[index]);
}
Just absolutely same thing using java 8 Stream API
Integer[] ints = {0,1,2,3,4,5,6,7,8,9};
IntStream.range(0, ints.length).filter(i -> i % 2 == 0).forEach(i -> System.out.println(ints[i]));
I assume this would be sufficient
// For loop to search array
for (int i = 0; i < array.length; i++) {
// If to validate that the index is divisible by 2
if (i % 2 == 0) {
System.out.print(array[i]);
}
}
This is what I did and it works:also I am not printing out index[0] because technically its not even thats why I started the for loop at 2. Your post did help me a lot. I also thank everyone else as well that took the time to post an answer.
import java.util.Scanner;
public class Arrayevenindex
{
public static void main(String[] args)
{
int number; // variable that will represent how many elements the user wants the array to have
Scanner key = new Scanner(System.in);
System.out.println(" How many elements would you like your array to have");
number = key.nextInt();
int [] array = new int [number];
// let the user enter the values of the array.
for ( int index = 0; index < number; index ++)
{
System.out.print(" Value" + (index+1) + " :");
array[index] = key.nextInt();
}
// Print out the even indexes
System.out.println("/nI am now going to print out the even indexes");
for ( int index = 2; index < array.length; index +=2)
{
System.out.print(array[index] + " ");
}
}
}
I created a java program that will search for a value in array but my problem is when I input the same value in a different index, the first index is the only one that will be on output.
Example index 0 = 2, index 1 = 3, index 2 = 2
Output : array 2 is found at index 0 only
I break it on the loop to stop but if I did not do that, it will loop the Output
Here's what I want for Output: array 2 is found at index 0,2
Code:
import java.awt.*;
import javax.swing.*;
import java.io.*;
public class Buff {
public static void main(String args[]) throws IOException {
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
System.out.print("Enter how many index :");
int v = Integer.parseInt( in .readLine());
int x;
int[] c = new int[v];
int vv;
for (x = 0; x < v; x++) {
System.out.print("Enter your value :");
c[x] = Integer.parseInt( in .readLine());
}
System.out.print("Enter your search number :");
int xx = Integer.parseInt( in .readLine());
for (x = 0; x < v; x++) {
if (c[x] == xx) {
System.out.print("array " + xx + " found at index :" + x);
break;
} else {
System.out.print("array not found");
}
}
}
}
You can also use StringBuilder if all you care is to output the indexes.
StringBuilder sb = new StringBuilder("array" + xx +" is found at index: ");
for (x = 0; x < v; x++) {
if (c[x] == xx) {
sb.append(x).append(",");
}
}
if (sb.charAt(sb.length() - 1) == ',') {
sb.deleteCharAt(sb.length() - 1);
System.out.println(sb);
} else {
System.out.println("array not found");
}
The solution to to make a list of the indexes that match and populate it in your for loop.
then after the for loop is done, print out the results
List<Integer> foundIndexes = new ArrayList<>();
for (x = 0; x < v; x++) {
if (c[x] == xx) {
foundIndexes.add(x);
}
}
//now we looped through whole array
if(foundIndexes.isEmpty()){
System.out.print("array not found");
}else{
System.out.print("array " + xx + " found at index : ");
for(Integer i : foundIndex){
System.out.print(i + ",");
}
}
This will print out array 2 is found at index 0,2, with a trailing comma. It's slightly more complicated to not have a trailing comma at the last index but I will leave that up to you to figure out.
If I understand correctly the problem is the following:
You have elements in an array, you want to check if a particular value is in more than once position of the array, your problem is if you simply remove the break statement, it shows a message every time you don't find the desired number, that's frankly the only problem I see with removing the break statement.
Personally, what I'd do one of these two things:
Option A: You can create a boolean variable that changes if you find a number, then wait to deliver the "array not found" message until you have stopped searching for it, like this:
boolean found = false;
for( x=0; x<v; x++)
{
if(c[x] == xx)
{
System.out.println("array " + xx + " found at index :"+x);
found = true;
}
}
if (found = false)
{
System.out.println("array not found");
}
println does the same as print, only it introduces a \n at the end, so the response looks like this:
array 2 found at index :0
array 2 found at index :2
Instead of:
array 2 found at index :0
array 2 found at index :2
Option B: Probably more elegant solution would be to create other array that store the positions in which you have found the element you are looking for, then print them all at once, you could do this going over the array twice (one to count how many positions the array has to have, another to check the positions of the elements) or simply use an ArrayList, but since this looks like learning material I'm going to guess that's out of the question.
Also if it is possible, try to word your question better because I'm still not even sure if this is what you are asking.
I need help printing the array, I need to print 6 items per line and switch to a next line for the seventh and following numbers. Also who do i Enter numbers into an array without defining how many numbers will be entered?
import java.util.Scanner;
public class NumberArray
{
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
System.out.println("How many grades do you want to enter?");
int num = input.nextInt();
int array[] = new int[num];
System.out.println("Enter the " + num + " grades now.");
for (int grades = 0 ; grades < array.length; grades++ )
{
array[grades] = input.nextInt();
}
System.out.println("These are the grades you have entered.");
printArray(array);
}
public static void printArray(int arr[])
{
int n = arr.length;
for (int i = 0; i < n; i++) {
System.out.print(arr[i] + " \t");
}
}
}
I need help printing the array, I need to print 6 items per line and switch to a next line for the seventh and following numbers.
From this question, it seems to indicate that you want the output to look like this:
1 2 3 4 5 6
7 8 9 ... n
This can be achieved quite simply.
Option 1 - The classic If statement
for(int x = 0; x < array.length; x++) {
System.out.print(array[x]);
if(x == 5) {
// 5 because we're counting from 0!
System.out.println();
}
}
Option 2 - Using the Ternary operator to keep it on one line
NOTE: This is more or less the same. It's just nice to be complete in these sorts of answers.
for(int x = 0; x < array.length; x++) {
System.out.print(array[x] + x == 5? "\n":"");
}
Edit
If you meant that you want 6 items on each line, like so:
1 2 3 4 5 6
7 8 9 10 11 12
...
Then you can use the % (The modulus operator) to print out a new line on every output. This is actually quite easy to change, but you'll need to make sure that you're checking the value before you're outputting the content. This can be shown in this IDEOne.
Use modulus operator (%) to break to a new line line:
public static void printArray(int arr[])
{
int n = arr.length;
for (int i = 0; i < n; i++) {
if(i % 6 == 0) // if you don't want the initial newline, check for i > 0
System.out.println()
System.out.print(arr[i] + " \t");
}
}
you can also use printf() method to format the line; which is probably better:
System.out.printf("%5d", arr[i]);
The reason why this is better, is because you can easily format the output to a specific justification, column width, etc., which will make your output look better.
my main purpose is to get this kind of a output: which shows the value and the number of times it appears in a array. Below is an example, but during the code, i will ask the user for input of data integers into an array
e.g. for the array: {-12, 3, -12, 4, 1, 1, -12, 1, -1, 1, 2, 3, 4, 2, 3, -12}
The output should be:
N Count
4 2
3 3
2 2
1 4
-1 1
-12 4
below here is my own attempt, but for some reason i could not get the array to be stored, and used at other parts of the code:
import java.util.*;
public class Q4
{
/**
* #param args
*/
public static void main(String[] args)
{
// TODO Auto-generated method stub
int[] myarray = new int[50];
System.out.println("Enter integers into the system, to quit enter -99");
Scanner scan=new Scanner(System.in);
for(int i = 0; i<myarray.length; i++)
{
int temp =scan.nextInt();
if(temp!=(-99))
{
myarray[i]=temp;
}
if(temp ==(-99))
{
System.out.println("Successfully terminated by inputting -99");
System.out.println();
break;
}
else if(i==(myarray.length-1))
{
System.out.println("successfully filled up array fully");
System.out.println();
}
}
for(int i = 0; i<myarray.length; i++)
{
System.out.print(myarray[i]+",");
}
System.out.print("}");
int temp=0;
int number = 0;
Arrays.sort(myarray);
System.out.println("Array list: {");
for (int i = 0; i < myarray.length; i++)
{
if(temp==0)
{
temp=myarray[i];
number++;
}
else if (temp!=0)
{
if (temp==myarray[i])
{
number++;
}
else
{
temp=0;
}
}
}
System.out.print("}");
System.out.println();
System.out.println();
System.out.println("N"+"\t"+"\t"+"Count");
System.out.println(temp+"\t"+"\t"+number);
}
}
here is My output, which isnt what i wanted,
Enter integers into the system, to quit enter -99
12
3123
3123
11
22
-99
Successfully terminated by inputting -99
Array list: {12,3123,3123,11,22,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,}Array list: {
}
N Count
3123 48
You increment number to attempt to count how many times the current array[i] has been seen, yet you never reset it's value to 0.
Also, at the end of your method, you are only printing a single row of the N Count table. If you want to print one row for each unique element of the index, don't you need to print more than one row?
There's an easier way to count the occurrences of elements in an array that doesn't require sorting it - hint, considering using a Map<Integer, Integer>.
You should try following thing.
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.Hashtable;
import java.util.Scanner;
public class NumberRepetion {
public static void main(String[] args) {
int[] myarray = new int[50];
System.out.println("Enter integers into the system, to quit enter -99");
Scanner scan = new Scanner(System.in);
ArrayList<Integer> myarrList = new ArrayList<Integer>();
while (scan.hasNext()) {
int temp = scan.nextInt();
if (temp != (-99)) {
// myarray[i] = temp;
myarrList.add(temp);
}
if (temp == (-99)) {
System.out.println("Successfully terminated by inputting -99");
System.out.println();
break;
}
}
Hashtable<Integer, Integer> result = new Hashtable<Integer, Integer>();
System.out.print("Input Values {");
int currIndex = 0 ;
for (Integer val : myarrList) {
if (currIndex == ( myarrList.size() - 1 )){
System.out.print(val);
}else{
System.out.print(val + ", ");
}
currIndex++ ;
int currVal = val;
Integer integer = result.get(currVal);
if (integer == null || integer == 0) {
result.put(currVal, 1);
} else {
result.put(currVal, ++integer);
}
}
System.out.print("}");
System.out.println()
Enumeration<Integer> keys = result.keys();
System.out.println("N\t\tCount");
while(keys.hasMoreElements()){
System.out.println(" " + keys.nextElement() +"\t\t" + result.get(keys.nextElement()));
}
//System.out.println("\n\n\n Result " + result);
}
}
OUTPUT
Enter integers into the system, to quit enter -99
5
6
5
8
4
-99
Successfully terminated by inputting -99
Input Values {5, 6, 5, 8, 4}
N Count
8 1
5 1
What I would do is to make a new node class that has two instances, the value and count. Every time you encounter a new number, make a new node with the its value, and increment its count by one. Have a List of the nodes and add the node to this list. For the next input, have a loop check if the value has already been seen before, eg.
for i = 0; i <list.size; i++
if list.get(i).data == value // if it finds the value increment and break
list.get(i).count++
break;
else if i==list.size-1//if it went through the list and didn't find the value, make a new node of the value and add it to the list
make a new node
add it to the list
After it has terminated, sort the list by comparing list.get(i).values and swapping (bubble sort comes to mind but there are many ways to sort)
After that just print the values and it's count
If this isn't a lesson how to use Arrays, I strongly advocate in making contact with List, and other collections - but preferably List, and concretely ArrayList. It is so convenient! And it is easy.
There are 3 or 4 basic operations: Constructor to define a List, add elements, remove elements, iterate over all elements.
And about 50 other not so frequently used methods, and methods which use Lists and so on.
public static void main (String [] args)
{
List <Integer> myarray = new ArrayList <Integer> ();
System.out.println ("Enter integers into the system, to quit enter -99");
Scanner scan = new Scanner (System.in);
while (scan.hasNextInt ())
{
int temp = scan.nextInt ();
if (temp == -99)
{
System.out.println ("Successfully terminated by inputting -99");
System.out.println ();
break;
}
else {
myarray.add (temp);
if (myarray.size () == 50)
{
System.out.println ("successfully filled array fully up");
System.out.println ();
}
}
}
for (int i : myarray)
{
System.out.print (i + ",");
}
System.out.print ("}");
Set <Integer> hsi = new HashSet <Integer> ();
hsi.addAll (myarray);
Collections.sort (myarray);
System.out.println ("Array list: {");
int idx = 0;
for (int i: hsi) {
System.out.println (i + "\t" + Collections.frequency (myarray, i));
}
System.out.println (myarray.size ());
}
See how short and simple? Just add the elements - you don't need to know in advance how many elements it contains. No marker-fields or external values to mark the end necessary!
Usage:
java Numbers
Enter integers into the system, to quit enter -99
4 44 0 33 2 2 7 9 1 4 3 90 -99
Successfully terminated by inputting -99
4,44,0,33,2,2,7,9,1,4,3,90,}Array list: {
0 1
1 1
2 2
3 1
33 1
4 2
7 1
9 1
44 1
90 1
12
Your first idea for collecting values, you like to get by index or you want to iterate over, should be ArrayList, not a plain old array. Array is only useful in exceptional cases - when you surely know the size in advance to begin with.
ArrayLists are fast, believe it - no - don't believe it, test it!