I am in learning java and I am at very beginner level.
My Question is : create 3 random number and put it into an array. No index in this array should contain 6 and 4. Then Show the output of the array with foreach loop. I am trying from last night but unable to get the solution. Please help me to overcome this problem. This is my code below :
Here is a sample that can get you the output that you are looking for:
int[] nums = new int[3];
for(int x = 0; x < nums.length; x++) {
int num = (int) (Math.random() * 10 + 1);
if(num == 6 | num == 4) {
x--;
continue;
}
else
nums[x] = num;
System.out.println(Arrays.toString(nums));
}
What we can do here is create a new random number each time through the loop. If the number is 6 or 4, we will activate a continue statement in order to start the loop over again, and we will also subtract -1 from x so that the loop doesn't start again. If the random number generated is not 6 or 4, we will store that number in the array with an index that corresponds with the iteration we are on. Each time through the loop we can print the updated array. If you want to create the random numbers first:
int x = 0;
int y = 0;
int z = 0;
int count = 0;
boolean isRunnin = true;
while(isRunnin) {
int num = (int) (Math.random() * 10 + 1);
if(num == 6 | num == 4) {
continue;
}
else {
if(count == 0) {
x = num;
}
else if(count == 1) {
y = num;
}
else if(count == 2) {
z = num;
}
}
count++;
if(count > 2) {
isRunnin = false;
}
}
System.out.println(x);
System.out.println(y);
System.out.println(z);
That will generate the three random numbers, and then you can place these numbers in the array in a for loop.
below should work
public static void main(String[] args)
{
firstThreeDigits() ;
}
public static void firstThreeDigits()
{
Random randomNumber= new Random();
int[] firstArray= new int[3];
for (int i = 0,j=0; ;j++) //i for array index and j for running loop until we get 3 numbers which are not 4 or 6
{
int number=randomNumber.nextInt(10);
if(!(number==4||number==6)) //if random number is NOT 4 or 6
{
firstArray[i]=number; // add to array
i++;
if(i==3) // print three number from array and break the loop
{
for(int num:firstArray)
{
System.out.println(num);
}
break;
}
}
}
}
Compilation errors are due to passing of int[] value to your firstThreeDigit() method. Removal of int[] value will although solve compilation problems but in that case your code might run multiple times to solve a single problem again and again.
This is perhaps what you want to achieve. Try refactoring your code in following way.
public static void main(String[] args){
firstThreeDigit();
}
public static void firstThreeDigit(){
Random rand = new Random();
int[] firstArray = new int[3];
int count = 0;
while(count < 3) {
int randomNumber = rand.nextInt(10);
if (randomNumber != 4 && randomNumber != 6) {
firstArray[count] = randomNumber;
count++;
}
}
for(int i : firstArray){
System.out.println(i);
}
}
I'm relatively new to java. I'm trying to find if numbers from 0 - 4 are stored
somewhere in an array of size 5. The array is populated by the user entering integers between 0-4. I have successfully managed to get it to confirm that the first number entered by the user is in the array however, the numbers after that not appearing.
So for example: If the user enters the numbers 2,2,2,1,3 I will get only 2 appears in the array as a result.
public static void checkEachNumber(int[] array)
{
int currentNum = 0;
for(int i = 0; i < array.length; i++)
{
for(int j = 0; j < array.length; j++)
{
currentNum = i;
if(currentNum == array[j])
{
System.out.println(currentNum + " appears in the array");
break;
}
else
{
System.out.println(currentNum + " doesn't appear in the array");
break;
}
}
}
}
To resolve your problem you should simply remove the have used in the else part of the array.
Consider a case like this
ex. 2 1 4 3
when checking for i=1 it will first compare the value with 2 so it will come out of the loop.
public static void checkEachNumber(int[] array)
{
int currentNum = 0;
for(int i = 0; i < array.length; i++)
{
int flag=0;
for(int j = 0; j < array.length; j++)
{
currentNum = i;
if(currentNum == array[j])
{
System.out.println(currentNum + " appears in the array");
flag=1;
break;
}
}
if(flag==0)
{
System.out.println("currentNum+"Doesn't appear in array");
}
}
}
When you execute a break statement, the loop stops running completely. In general, the way to scan for a match is going to look like this:
found_match = no
for (... in ...) {
if (match) {
found_match = yes
break
}
}
if (found_match) {
do_found_match_stuff();
}
I start learning programming about 4 days ago by myself and iam a lil bit stuck with 2d arrays. I try to challenging myself with tasks, like get from 2d array column with most zeros or atleast just count zeros, so far i get this far
public class b {
public static void main(String[] args) {
int a[][] = new int [5][5];
int i,j;
int s = 0;
for(i= 0;i<a.length; i++)
for(j = 0; j<a[i].length; j++){
a[i][j] = (int)(Math.random()*10);
}
for(i=0;i<a.length;i++){
for(j=0;j<a[i].length;j++) {
System.out.print(a[i][j] + "\t");
}
System.out.println();
}
for(j=0;j<a[0].length;j++) {
for(i=0;i<a.length;i++) {
if(a[i][j] >-1 || a[i][j]<1) {
s++;
System.out.println(s +"\t");
s = 0;
}
}
}
}
}
Can somebody explain me why result is always 1 and why it counts columns and rows in one row?
Suppose the condition enters into if(a[i][j] >-1 || a[i][j]<1) then you increase s by 1 then print it which gives 1 then you reassign it to s=0 so it gives same 1 each time.So remove the s=0 and place the printing line after end of loop
public class b {
public static void main(String[] args) {
int a[][] = new int [5][5];
int i,j;
int s = 0;
for(i= 0;i<a.length; i++)
for(j = 0; j<a[i].length; j++){
a[i][j] = (int)(Math.random()*10);
}
for(i=0;i<a.length;i++){
for(j=0;j<a[i].length;j++)
System.out.print(a[i][j] + "\t");
System.out.println();
}
for(j=0;j<a[0].length;j++){
for(i=0;i<a.length;i++)
if(a[i][j] >-1 && a[i][j]<1){
s++;
}
System.out.println("Zero in column no. "+j+" is "+s +"\t");
s=0;
}
}
}
Demo
Result will be 1 because you're re-assigning 0 to s everytime. But the issue is not only that.
Firstly your condition is using wrong indices. Instead of a[i][j] you should use a[j][i] as you're traversing column-wise. Secondly:
if(a[j][i] >-1 || a[j][i]<1){
can be simply written as:
if(a[j][i] == 0) {
So the structure is the outer for loop will iterate over each column number. And for each column number, inner for loop will find count of 0. You've to maintain a max variable outside both the loops, to track the current max. Also, you've to use another variable inside the outer for loop to store the count for current column.
Everytime the inner for loop ends, check if current column count is greater than max. If yes, reset max.
int max = 0;
for(j=0;j<a[0].length;j++){
int currentColumnCount = 0;
for(i=0;i<a.length;i++) {
if(a[j][i] == 0) {
currentColumnCount++;
}
}
if (currentColumnCount > max) {
max = currentColumnCount;
}
}
I'm trying to write a java method which finds all the modes in an array. I know there is a simple method to find the mode in an array but when there are more than one single mode my method outputs only one of them. I've tried to find a way but am nit sure how to approach this problem. Can anyone help me out to find all the modes in the array? Thanks.
Yes here is my code which outputs only one mode even if multiple modes exist.
public static int mode(int a[]){
int maxValue=0, maxCount=0;
for (int i = 0; i < a.length; ++i){
int count = 0;
for (int j = 0; j < a.length; ++j){
if (a[j] == a[i]) ++count;
}
if (count > maxCount){
maxCount = count;
maxValue = a[i];
}
}
return maxValue;
}
okay here's an example:
30
30
30
34
34
23
In this set of numbers there is only one mode, which is 30.
30
30
30
34
34
34
23
But in this set there are two modes, 30 and 34. I want my code to be able to output both of them, whereas it only prints one. It prints only 30.
The following code will return you an Integer[] containing the modes. If you need an int[] instead, you still need to convert the Integer instances to ints manually. Probably not the most efficient version, but its matches closely to your code
public static Integer[] mode(int a[]){
List<Integer> modes = new ArrayList<Integer>( );
int maxCount=0;
for (int i = 0; i < a.length; ++i){
int count = 0;
for (int j = 0; j < a.length; ++j){
if (a[j] == a[i]) ++count;
}
if (count > maxCount){
maxCount = count;
modes.clear();
modes.add( a[i] );
} else if ( count == maxCount ){
modes.add( a[i] );
}
}
return modes.toArray( new Integer[modes.size()] );
}
After a long night of programming, I finality got a program that will print out the mode/modes of an array. Or will even tell you if there isn't a mode (say, if no input occurred more than once or all the inputs occurred the same amount of times: ex. 1, 1, 2, 2, 3, 3, 4, 4). Some limitations of the program are that you must enter more than one number, and you cannot enter more than 10000 numbers or a negative number (if you wanted to enter a negative number, you would just have to tweak all the for loops involving the values[][] array. Some cool things about my program are that it prints out how many times each of you inputs occurred along with the mode of your array. And all of the print outs grammar change according to the amount of info (Ex. The mode of your array is 2; The modes of your array are 1 & 2; The modes of your array are 0, 2, 5, & 8). There is also a bubble sort function example in the program for anyone who thought that they needed a sorter function in their mode program. Hope this helps, I included a lot of pseudo code to help anyone who doesn't see how my logic progress throughout the program. (FYI: It is java, and was compiled in BlueJ)
import java.util.Scanner;
public class Mode
{
public static void main (String args [])
{
Scanner scan = new Scanner(System.in);
int MAX_INPUTS = 10000; boolean flag = false;
System.out.print ("Input the size of your array: ");
int size; // How many nubers will be in the user array
do
{
size = scan.nextInt();
if (size == 1)
{
System.out.print ("\nError. You must enter a number more than 1.\n\n");
continue;
}
else if (size > MAX_INPUTS || size < 0)
{
System.out.print ("\nError. You muste enter a number less than " + MAX_INPUTS + " or greater than 0\n\n");
continue;
}
else
flag = true; // a ligit answer has been entered.
}
while (flag != true);
int array[] = new int[size], values[][] = new int[2][MAX_INPUTS + 1], ticks = 0;
System.out.print ("\nNow input the numbers for your array.\n\n");
/* Taking inputs from the user */
while (ticks < size)
{
System.out.print ("Number " + (ticks + 1) + ": ");
array[ticks] = scan.nextInt();
if (array[ticks] > MAX_INPUTS || array[ticks] < 0)
{
System.out.print ("\nError. Number cannot be greater than " + MAX_INPUTS + " or less than 0\n\n");
continue;
}
++ticks;
}
/*
* values[][] array will hold the info for how many times numbers 0 - 10000 appear in array[]. Column 0 will hold numbers from 0 -1000, and column 1 will hold the number of
* of repititions the number in column 0 occured in the users inputed array.
*/
for (int i = 0; i < MAX_INPUTS; ++i) // Initalize Column zero with numbers starting at zeor, and ending and MAX_INPUTS.
values[0][i] = i;
for (int i = 0; i < size; ++i) // Find the repatitions of the numbers in array[] that correspond to the number in column zere of values[][].
for (int j = 0; j < MAX_INPUTS; ++j)
if (array[i] == j)
++values[1][j];
sort (array, size);
System.out.print ("\n\nHere are the numbers you entered.\n\n"); // show the values the user entered in ascending order.
for (int i = 0; i < size; ++i)
{
if (i == size - 1) // the last inputed number
System.out.print (array[i]); // don't allow an extra comma.
else
System.out.print (array[i] + ", ");
}
// Show the user how many times each of the values he/she entered occured.
System.out.print ("\n\nThis is the amount of times each of the values you entered occured:\n");
for (int i = 0; i < MAX_INPUTS; ++i)
{
if (values[1][i] == 1)
System.out.print (i + " was entered " + values[1][i] + " time\n"); // avoid: 2 was entered 1 times
else if (values[1][i] != 0)
System.out.print (i + " was entered " + values[1][i] + " times\n"); // avoid: 2 was entered 2 time
}
/* -------------------------------------------------------------------- | Finding the Mode/Modes | -------------------------------------------------------------------- */
/* The process begins with creating a second array that is the exactly the same as the values[][] (First for loop). Then I sort the duplicate[] array to find the mode
* (highest number in the duplicate[]/values[][] arrays. Int max is then assigned the highest number. Remembering that the values[][] array: column 0 contains numbers ranging
* from 1 to 10000, it keeps track of where the numbers in column were originally located, in which you can compare to the duplicate array which is sorted. Then I can set
* up a flag that tells you whether there is more than one mode. If so, the printing of these modes will look neater and the grammar can be changed accordingly.
*/
int duplicate[] = new int [10001], mode[] = new int [size], max, mode_counter = 0;
boolean multi_mode = false, all_same;
for (int i = 0; i < MAX_INPUTS; ++i)
duplicate[i] = values[1][i]; // copy values array.
sort (duplicate, MAX_INPUTS);
max = duplicate[MAX_INPUTS - 1]; // the last number in the sorted array is the greatest.
all_same = test (duplicate, MAX_INPUTS, size, max); // this is the test to see if all the numbers in the user array occured the same amount of times.
int c = 0; // a counter
/* The mode of the user inputed array will be recorded in the values array. The sort of the duplicate array told me what was the higest number in that array. Now I can
* see where that highest number used to be in the original values array and recored the corresponding number in the column zero, which was only filled with numbers 0 -
* 10000. Thus telling me the mode/modes.
*/
for (int i = 0; i < MAX_INPUTS; ++i)
{
if (values[1][i] == max)
{
mode[c++] = values[0][i];
++mode_counter;
}
}
if (mode[1] != 0) //mode[0] (the first cell, has a number stored from the last for loop. If the second cell has a number other than zero, that tells me there is more than 1 mode.
multi_mode = true;
if (multi_mode == false)
System.out.print ("\nThe mode of your array is " + mode[0]); // For correct grammer.
else if (all_same == true)
System.out.print ("\nAll of the numbers entered appeared the same amount of times. "); // See the boolean function for more details
else // If here there is more than one mode.
{
System.out.print ("\nThe modes of yoru array are ");
for (int i = 0; i < mode_counter; ++i)
{
if (mode_counter > 2 && i == (mode_counter - 1)) // If there is more than two modes and the final mode is to be printed.
System.out.print ("& " + mode[i]);
else if (mode_counter == 2)
{ // This is true if there is two modes. The else clause will print the first number, and this will print the amper sign and the second mode.
System.out.print (mode[0] + " & " + mode[1]);
break;
}
else
System.out.print (mode[i] + ", ");
}
}
}
public static void sort (int list[], int max) // Its the bubble sort if you're wondering.
{
int place, count, temp;
for (place = 0; place < max; ++place)
for (count = max - 1; count > place; --count)
if (list[count - 1] > list[count])
{
temp = list[count-1];
list[count - 1] = list[count];
list[count] = temp;
}
}
/* The test to see if there isn't a mode. If the amount of the mode number is the same as the amount of numbers there are in the array is true, or if the size entered by the
* user (input) modulo the mode value is equal to zero (say, all the numbers in an array of ten were entered twice: 1, 1, 2, 2, 3, 3, 4, 4, 5, 5). */
public static boolean test (int list[], int limit, int input, int max)
{
int counter = 0, anti_counter = 0;
for (int i = 0; i < limit; ++i)
if (list[i] == max)
++counter; // count the potential modes
else if (list[i] !=0 && list[i] != max)
++anti_counter; // count every thing else except zeros.
if (counter == input || (input % max == 0 && anti_counter == 0) )
return true;
else
return false;
}
}
Even though this probably isn't the most efficient solution, it will print all the highest modes:
public static int mode(int a[]) {
int maxValue=-1, maxCount=0;
for (int i = 0; i < a.length; i++) {
int count = 0;
for (int j = 0; j < a.length; j++) {
if (a[j] == a[i])
count++;
}
}
if (count > maxCount) {
maxCount = count;
maxValue = a[i];
}
}
//loop again and print only the highest modes
for (int i = 0; i < a.length; i++) {
int count = 0;
for (int j = 0; j < a.length; j++) {
if (a[j] == a[i])
count++;
}
}
if (count == maxCount) {
System.out.println(a[i]);
}
}
}
Hope this helps. This is my answer. Hope it helps
public List mode(double[] m) {
HashMap<Double, Double> freqs = new HashMap<Double, Double>();
for (double d : m) {
Double freq = freqs.get(d);
freqs.put(d, (freq == null ? 1 : freq + 1));
}
List<Double> mode = new ArrayList<Double>();
List<Double> frequency = new ArrayList<Double>();
List<Double> values = new ArrayList<Double>();
for (Map.Entry<Double, Double> entry : freqs.entrySet()) {
frequency.add(entry.getValue());
values.add(entry.getKey());
}
double max = Collections.max(frequency);
for(int i=0; i< frequency.size();i++)
{
double val =frequency.get(i);
if(max == val )
{
mode.add(values.get(i));
}
}
return mode;
}
Handling multiple mode values:
Here initially I am taking a map to get the frequencies of each element. After finding the max repeating value I am storing its map value.
While iterating to the map I am checking if this value is repeating for some key and is not 1, if it is then I am adding that key as well. This will get me the multiple modes
public static void mode(int a[]){
int count=0;
Map<Integer,Integer> map=new HashMap<>();
for(int i=0;i<a.length;i++)
{
map.put(a[i],map.getOrDefault(a[i],0)+1);
}
Set<Integer> set=new HashSet<>();
int maxValue=0;
for(int i=0;i<a.length;i++)
{
int ct=0;
for(int j=0;j<a.length;j++)
{
if(a[i]==a[j])
ct++;
}
if(ct>count)
{
count=ct;
maxValue=a[i];
}
}
set.add(maxValue);
int k=map.get(maxValue);
if(k!=1)
{
for(Map.Entry m:map.entrySet())
{
if((int)m.getValue()==k)
set.add((int)m.getKey());
}
}
System.out.println("Mode: "+set);
}
I am trying to write a program that generates all the subsets of an entered set in java. I think i nearly have it working.
I have to use arrays (not data structures)
The entered array will never be greater than 20
Right now when i run my code this is what i get:
Please enter the size of A: 3
Please enter A: 1 2 3
Please enter the number N: 3
Subsets:
{ }
{ 1 }
{ 1 2 }
{ 1 2 3 }
{ 2 3 }
{ 2 3 }
{ 2 }
{ 1 2 }
this is the correct number of subsets (2^size) but as you can see it prints a few duplicates and not some of the subsets.
Any ideas where I am going wrong in my code?
import java.util.Scanner;
public class subSetGenerator
{
// Fill an array with 0's and 1's
public static int [] fillArray(int [] set, int size)
{
int[] answer;
answer = new int[20];
// Initialize all elements to 1
for (int i = 0; i < answer.length; i++)
answer[i] = 1;
for (int a = 0; a < set.length; a++)
if (set[a] > 0)
answer[a] = 0;
return answer;
} // end fill array
// Generate a mask
public static void maskMaker(int [] binarySet, int [] set, int n, int size)
{
int carry;
int count = 0;
boolean done = false;
if (binarySet[0] == 0)
carry = 0;
else
carry = 1;
int answer = (int) Math.pow(2, size);
for (int i = 0; i < answer - 1; i++)
{
if (count == answer - 1)
{
done = true;
break;
}
if (i == size)
i = 0;
if (binarySet[i] == 1 && carry == 1)
{
binarySet[i] = 0;
carry = 0;
count++;
} // end if
else
{
binarySet[i] = 1;
carry = 1;
count++;
//break;
} // end else
//print the set
System.out.print("{ ");
for (int k = 0; k < size; k++)
if (binarySet[k] == 1)
System.out.print(set[k] + " ");
System.out.println("}");
} // end for
} // maskMaker
public static void main (String args [])
{
Scanner scan = new Scanner(System.in);
int[] set;
set = new int[20];
int size = 0;
int n = 0;
// take input for A and B set
System.out.print("Please enter the size of A: ");
size = scan.nextInt();
if (size > 0)
{
System.out.print("Please enter A: ");
for (int i = 0; i < size; i++)
set[i] = scan.nextInt();
} // end if
System.out.print("Please enter the number N: ");
n = scan.nextInt();
//System.out.println("Subsets with sum " + n + ": ");
System.out.println("Subsets: ");
System.out.println("{ }");
maskMaker(fillArray(set, size), set, n, size);
} // end main
} // end class
The value of i always goes from 0 to N-1 and then back to 0. This is not useful to generate every binary mask you need only one time. If you think about it, you need to move i only when you have generate all possible masks up to i-1.
There is a much easier way to do this if you remember every number is already internally represented in binary in the computer and everytime you increment it Java is doing the adding and carrying by itself. Look for bitwise operators.