This question already has answers here:
Sort an array in Java
(19 answers)
Closed 7 years ago.
Can someone help me to continue this code using array?this is the sample output
Enter number of element(2-10): 5
Element[1]: -3
Element[2]: 0
Element[3]: 10
Element[4]: 2
Element[5]: 7
Max Value is: 10
Min Value is: -3
Ascending order: -3 0 2 7 10
Descending order: 10 7 2 0 -3
I only have this code.
import java.util.Scanner;
public class Array1 {
public static void main(String[] args) {
Scanner n = new Scanner(System. in );
int num[] = new int[];
int ne = 0;
int e = 0;
System.out.print("Enter Number of Elements(2-10): ");
ne = n.nextInt();
for (int x = 1; x <= ne; x++) {
System.out.print("Element[" + x + "]: ");
e = n.nextInt();
}
}
}
The output of this is:
Enter number of element(2-10): 5
Element[1]: -3
Element[2]: 0
Element[3]: 10
Element[4]: 2
Element[5]: 7
Then I don't know how to get the others.
I can share the logic but not the code.
The input numbers from user can be added to an array.
Arrays.sort() can be used to sort in ascending or descending order.
Reference: Arrays Sort and Reverse order
Change code to below
1.) Take user input first for creating array with size ne.
2.) Initialize your array with size ne.
3.) In loop, keep getting and putting elements in array.
public static void main(String[] args) {
Scanner n = new Scanner(System.in);
int ne = 0;
int e = 0;
System.out.print("Enter Number of Elements(2-10): ");
ne = n.nextInt();
int num[] = new int[ne];
for (int x = 0; x < ne; x++) {
System.out.print("Eneter element");
num[x] = n.nextInt();
}
System.out.println("original " + num);
}
For Sorting, please try youserf first and then post
Related
This is the Prompt:
This is what I wrote:
import java.util.Scanner;
public class ContagionControl {
public static void main(String[] args) {
System.out.println("Please Enter the Number of Citizens: ");
Scanner input= new Scanner(System.in);
int a = input.nextInt();
int[] A = new int [a];
System.out.printf(" Id");
for (int i=0; i< A.length; i++) {
System.out.printf("%4d", i);
}
System.out.println();
System.out.printf("Cantactee");
for (int i=0; i< A.length; i++) {
int b= (int) (Math.random() * A.length);
System.out.printf ("%4d", b);
}
System.out.println();
System.out.println("Please Enter the Number of Citizens");
int c = input.nextInt();
for (int j=0; )
}
}
How can I match the infected id with his/her contactee ?
you need to create another ArrayList to hold quarantine_citizens;
step 1 Then get the contactee from to the citizen array base (index of citizen, map index to contactee array)
create variable to hold contactee and put into quarantine_citizens ArrayList
and it needs to map to the citizen array again ( do step 1 again )
#Jay explained the required algorithm in his answer. Below is the code that implements the algorithm.
The following appears in the assignment instructions that you posted in your question:
use the shuffling algorithm
And also
Be aware that all the elements are distinct
Your shuffling algorithm does not ensure that all elements are distinct. In other words, the algorithm that appears in the code in your question may produce the same number more than once.
The below code uses code taken from this Web page:
Shuffle Array in Java
The below code also checks for valid user input. More explanation appears after the code.
import java.util.ArrayList;
import java.util.Collections;
import java.util.InputMismatchException;
import java.util.List;
import java.util.Random;
import java.util.Scanner;
public class CC {
private static int[] getCitizens(int numberOfCitizens) {
int[] citizens = new int[numberOfCitizens];
for (int i = 0; i < numberOfCitizens; i++) {
citizens[i] = i;
}
return citizens;
}
private static int[] getContactees(int[] array, int a) {
int[] contactees = new int[array.length];
System.arraycopy(array, 0, contactees, 0, array.length);
Random rd = new Random();
// Starting from the last element and swapping one by one.
for (int i = a - 1; i > 0; i--) {
// Pick a random index from 0 to i
int j = rd.nextInt(i + 1);
// Swap array[i] with the element at random index
int temp = contactees[i];
contactees[i] = contactees[j];
contactees[j] = temp;
}
return contactees;
}
private static void printArray(int[] array, String format, String prompt) {
System.out.print(prompt);
for (int i : array) {
System.out.printf(format, i);
}
System.out.println();
}
private static void printResult(List<Integer> list) {
System.out.println("These citizens are to be self-isolated in the following 14 days:");
for (Integer id : list) {
System.out.print(id + " ");
}
System.out.println();
}
public static void main(String[] args) {
#SuppressWarnings("resource")
Scanner input = new Scanner(System.in); // Don't close 'Scanner' that wraps stdin.
// (Even though IDE warns that you should.)
int numberOfCitizens = 0;
do {
System.out.print("Number of citizens: ");
try {
numberOfCitizens = input.nextInt();
if (numberOfCitizens <= 0) {
System.out.println("Must be positive integer. Try again.");
}
}
catch (InputMismatchException xInputMismatch) {
System.out.println("Not an integer. Try again.");
input.nextLine();
}
} while (numberOfCitizens <= 0);
int[] citizens = getCitizens(numberOfCitizens);
String format = "%" + Integer.toString(numberOfCitizens).length() + "d ";
printArray(citizens, format, " ID ");
int[] contactees = getContactees(citizens, numberOfCitizens);
printArray(contactees, format, "Contactee ");
int infectedCitizen = -1;
int limit = numberOfCitizens - 1;
do {
System.out.printf("ID of infected citizen [0-%d]: ", limit);
try {
infectedCitizen = input.nextInt();
if (infectedCitizen < 0 || infectedCitizen > limit) {
System.out.println("Not within range. Try again.");
}
}
catch (InputMismatchException xInputMismatch) {
System.out.println("Not an integer. Try again.");
input.nextLine();
}
} while (infectedCitizen < 0 || infectedCitizen > limit);
List<Integer> infected = new ArrayList<>(numberOfCitizens);
while (true) {
if (!infected.contains(infectedCitizen)) {
infected.add(infectedCitizen);
infectedCitizen = contactees[infectedCitizen];
}
else {
break;
}
}
Collections.sort(infected);
printResult(infected);
}
}
The last while loop, in method main is the actual algorithm. All preceding code is just preparation. I refer to the following code:
List<Integer> infected = new ArrayList<>(numberOfCitizens);
while (true) {
if (!infected.contains(infectedCitizen)) {
infected.add(infectedCitizen);
infectedCitizen = contactees[infectedCitizen];
}
else {
break;
}
}
I now use the sample data from your question to explain the above algorithm. Here is the sample data:
ID 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
Contactee 2 0 7 11 15 4 14 1 8 13 3 5 12 9 6 10
We create an empty List.
The user-entered ID is 0 (zero).
We add 0 to the List.
We get the element in Contactee array at index 0 – which is 2
We add 2 to the List.
We get the element in Contactee array at index 2 – which is 7
We add 7 to the List.
We get the element in Contactee array at index 7 – which is 1
We add 1 to the List.
The element in Contactee at index 1 is 0. Since 0 already appears in the List, we are done.
List now contains all the infected citizens, namely 0, 1, 2 and 7.
Note that sorting the list is only to display the list in ascending order. It is not required.
Here is output from a sample run of the above code:
Number of citizens: 16
ID 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
Contactee 5 8 3 0 11 12 14 9 7 1 15 2 4 13 6 10
ID of infected citizen [0-15]: 0
These citizens are to be self-isolated in the following 14 days:
0 2 3 4 5 11 12
I wanted to check if frequency of minimum element is odd: I would print lucky, otherwise print "Unlucky".
I used a technique related to counting sort arr[arr1[i]]++ counting duplicated as value and reference to the actual value to it's INDEX. I tried with this but it didn't bring the correct answer [appreciate if you correct my code rather than a new different solution]
input: 6 6 6 4 4 4 4 3 3 3 7 7
output: Unlucky
since the minimum frequency is 7, 7%2!=0 so Unlucky
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int t=in.nextInt();
while(t-->0) { //Test cases
int n=in.nextInt();//array's length
int arr[]=new int[n];// array
for(int i=0;i<arr.length;i++) {
arr[i]=in.nextInt();
}
int counter[]=new int[256];//counting duplicates
for(int i=0;i<arr.length;i++) {
counter[arr[i]]++;
}
int min=1;
int pos=0;
for(int i=0;i<counter.length;i++) {
if(counter[i]<min && counter[i]!=0) { //search for minimal frequency (counter[i]!=0 since our counter array could easily have lot zeroes
min=counter[i];
pos=i;
}
}
System.out.println((pos%2==0)?"Unlucky":"Lucky");
}
}
There is no need to the while loop and other loop for counter, you assign the array using n variable,
then you enter values to the arr and check frequency in the same loop.
And select the min frequency to check if it's lucky or not
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int n = in.nextInt();// array's length
int arr[] = new int[n];// array
int counter[] = new int[n];
int min = 1;
int pos = 0;
for (int i = 0; i < arr.length; i++) {
arr[i] = in.nextInt();
counter[arr[i]]++;
if (counter[i] < min && counter[i] != 0) {
min = counter[i];
pos = i;
}
}
System.out.println((pos % 2 == 0) ? "Unlucky" : "Lucky");
in.close();
}
, input
12 6 6 6 4 4 4 4 3 3 3 7 7
, output
Unlucky
Consider the following points:
Your program is less useful/efficient for three reasons: (A) It will work for integers from 0 to 255 only (B) You are using a fixed size array of size 256 which means that even if the user enters just a few numbers, it will consume space for 256 integers (C) You are iterating the loop 256 times to calculate the frequency even if the user enters just a few numbers.
There are so many ways to count the frequency of numbers. Commonly people use a Map to do so. I've used the same thing in the function, minFrequencyNumber shown below:
import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.print("Enter the size of array: ");
int n = in.nextInt();
int arr[] = new int[n];
System.out.print("Enter " + n + " integers: ");
for (int i = 0; i < arr.length; i++) {
arr[i] = in.nextInt();
}
System.out.println("The number with minimum frequency is: " + minFrequencyNumber(arr));
System.out.println((minFrequencyNumber(arr) % 2 == 0) ? "Unlucky" : "Lucky");
}
public static int minFrequencyNumber(int[] arr) {
Map<Integer, Integer> m = new HashMap<>();
// Iterate the array
for (int i : arr) {
// If the number does not exist in the Map, put the number as the key and 1 as
// the value (frequency); otherwise, put the number as the key in the map by
// increasing its value (frequency) by 1
m.put(i, m.getOrDefault(i, 0) + 1);
}
int num = 0, minFrequency = Integer.MAX_VALUE;
// Iterate the map
for (Entry<Integer, Integer> e : m.entrySet()) {
if (e.getValue() < minFrequency) {
minFrequency = e.getValue();
// Store the key (the number) whose frequency is minimum
num = e.getKey();
}
}
return num;
}
}
A sample run:
Enter the size of array: 12
Enter 12 integers: 6 6 6 4 4 4 4 3 3 3 7 7
The number with minimum frequency is: 7
Lucky
This question already has answers here:
minimum value in java won't work
(4 answers)
Closed 4 years ago.
my code is not working because it is always printing small value as 0.
Thanks in advance for your help.
public class Tests {
public static void main(String [] args){
int [] num=new int[10];
Random random= new Random();
//1st time both big and small value will be at 0
int big=num[0];
int small=num[0];
for(int i=0;i<num.length;i++){
num[i]=random.nextInt(10);
System.out.print(num[i] +" ");
if(num[i]>big){
big=num[i];
}
if(num[i]<small){
small=num[i];
}
}
System.out.println();
System.out.println("Big " + big);
System.out.println("Small " + small);
}
}
See below the issue:
Good Result:
5 1 1 3 8 3 5 1 1 0
Big 8
Small 0
Bad Result:
6 8 8 1 7 5 2 6 8 4
Big 8
Small 0
This is because small is 0 and every random value will be generated between 0 and 10, so 0 is the smallest.
To fix it, change to
int small = Integer.MAX_VALUE;
When you initiated the int array int [] num=new int[10]; it assigned zero(0) to all index.
So, when you let int small=num[0]; it contain zero(0)
So, whatever the value are coming, following block always comparing small as zero(0). So, not changing the small variable!
if(num[i]<small){
small=num[i];
}
assign int small=Integer.MAX_VALUE; AND int big=Integer.MIN_VALUE; then it will all work!
Declare int small as:
int small = Integer.MAX_VALUE;
And now it will work.
Note: And also it is better to declare int big as
int big = Integer.MIN_VALUE;
init array in another loop. when you init int array all of them are 0.
public class Test {
public static void main(String[] args) {
int[] num = new int[10];
Random random = new Random();
for (int i = 0; i < num.length - 1; i++) {
num[i] = random.nextInt(10);
}
//1st time both big and small value will be at 0
int big = num[0];
int small = num[0];
for (int i = 0; i < num.length - 1; i++) {
System.out.print(num[i] + " ");
if (num[i] > big) {
big = num[i];
}
if (num[i] < small) {
small = num[i];
}
}
System.out.println();
System.out.println("Big " + big);
System.out.println("Small " + small);
}
}
When you say int [] num=new int[10]; , num array will be initialized with 0 for all 10 places i.e. num[0]= 0, num[1]=0...
and so as suggested by others use int small = Integer.MAX_VALUE;
Always remember, when you initialize something to a variable which stores the biggest, initialize a small value like 0 and for a small variable initialize it with the biggest number possible.
I've figured out how to create an array in which the output look like this:
1 2 3 4
5 6 7 8
9 10 11 12
13 14 15 16
if the user enters a 4 indicating a 4x4 array.
My question is how could I manipulate this code in a way that it would out put the array in this order
1 2 3 4
8 7 6 5
9 10 11 12
16 15 14 13
where every other row is "backwards"
`import java.util.Scanner;
import java.util.Arrays;
import java.util.Arrays;
public class Question2 {
public static void main(String[] args) {
//Title
System.out.println("[----------------------]");
System.out.println("[ Array Pattern ]");
System.out.println("[----------------------]");
System.out.println("");
//declare scanner
Scanner keyboard = new Scanner (System.in);
//Prompt user to enter a digit greater than or equal to 3
System.out.println("How many rows/columns do you want your array to have? (Must be at least 3):");
//read user input
int num = keyboard.nextInt();
//place constraints on int num so that if it is less than 3, the program does not execute
while(num<3 )
{
System.out.println("Lets's try this again....");
System.out.println("How many rows/colums do you want your array to have? (Must be at least 3):");
num = keyboard.nextInt();
}
//2D array with number of rows and columns entered by user
int[][] array = new int [num][num];
int inc=1;
for(int i=0;i<array.length;i++)
for(int j=0;j<array.length;j++)
{
array[i][j]=inc;
inc++;
}
//replace all square brackets in array display & format into order
//replace all commas in array display
String a = Arrays.toString(array);
a = Arrays.deepToString(array).replace("], [", "\n").replaceAll("[\\[\\],]", "");
System.out.println(a);`
This loop will do it:
int reverse = 0;
for(int i=0;i<array.length;i++)
for(int j=0;j<array.length;j++)
{
if(i%2 == 0){
if(j == 0){
inc = reverse;
if(i > 0 )inc = inc + num + 1;
}
array[i][j]=inc;
inc++;
}
else{
if(j == 0)reverse = inc + num - 1;
array[i][j]=reverse;
reverse--;
}
}
Every other row it place numbers in a descending order.
Also to print out the numbers with tabs between them use:
String a = Arrays.toString(array);
a = Arrays.deepToString(array).replace("], [", "\n").replace(", ", "\t").replaceAll("[\\[\\],]", "");
System.out.println(a);
This will stop a table forming diagonally.
What you could do is reverse the order of the for loop on every other line, so that it decrements instead:
for(int i=0;i<array.length;i++)
{
if(i%2 == 0){
for(int j=0;j<array.length;j++)
{
array[i][j]=inc;
inc++;
}
}
else{
for(int j=num-1;j>=0;j--)
{
array[i][j]=inc;
inc++;
}
}
}
I don't really know how to format the columns the way you wrote the code (with Arrays.deepToString) but if you instead loop through it manually you could pad the string:
String [][]stringConvertedTable= new String[num][num];
for(int i=0; i<num; i++) {
for(int j=0; j<num; j++) {
stringConvertedTable[i][j]= Integer.toString(array[i][j]);
System.out.print(stringConvertedTable[i][j] + "\t");
}
System.out.println("");
}
It's not the most elegant way to do it though...
//MY TASK IS TWO MERGE TO ARRAYS INTO ASCENDING ORDER.Your program will accept each array as input from the keyboard. You do not know ahead of time how many values will be entered, but you can assume each array will have a maximum length of 10,000 elements. To stop entering values enter zero or a negative number. You should disregard any non-positive numbers input and not store these in the array.
The elements of the two input arrays should be in increasing order. In other words, each array element must have a value that is greater than or equal to the previous element value. An array may contain repeated elements.
import java.util.Scanner;
import java.lang.Math;
class Main {
public static void main(String[] args){
Scanner scan = new Scanner(System.in);
int one[]= new int[10000];
int two[]= new int[10000];
int lengthShort=0;
int lengthLong=0;
int a =0;
int b =0;
System.out.println("Enter the values for the first array, "
+ "up to 10000 values, enter a negative number to quit");
for(int i=0; i<one.length && scan.hasNext(); i++){
one[i] = scan.nextInt();
a++;
if(one[i]<0){
one[i]=0;
break;
}
}
int length1 = a-1;
System.out.println("Enter the values for the second array, "
+ "up to 10000 values, enter a negative number to quit");
for(int i=0; i<two.length && scan.hasNext(); i++){
two[i] = scan.nextInt();
b++;
if(two[i]<0){
two[i]=0;
break;
}
}
int lengthTwo = b-1;
int mergeOne[] = new int[length1];
for (int i = 0; i<mergeOne.length; i++){
mergeOne[i]=one[i];
}
int mergeTwo[] = new int[lengthTwo];
for (int i = 0; i<mergeTwo.length; i++){
mergeTwo[i]=two[i];
}
System.out.println("First Array:");
for(int i=0; i<mergeOne.length; i++){
System.out.print(mergeOne[i] + " ");
}
System.out.println("\nSecond Array:");
for(int i=0; i<mergeTwo.length; i++){
System.out.print(mergeTwo[i] + " ");
}
if(mergeOne.length<=mergeTwo.length){
lengthLong = mergeTwo.length;
lengthShort = mergeOne.length;
}
else if(mergeOne.length>=mergeTwo.length){
lengthShort = mergeTwo.length;
lengthLong = mergeOne.length;
}
int merged[] = new int[length1 + lengthTwo];
for(int i = 0; i<lengthShort; i++){
if(i==0){
if(mergeOne[i]<=mergeTwo[i]){
merged[i] = mergeOne[i];
merged[i+1] = mergeTwo[i];
}
else if(mergeTwo[i]<=mergeOne[i]){
merged[i] = mergeTwo[i];
merged[i+1]= mergeOne[i];
}
}
else if(i>0){
if(mergeOne[i]<=mergeTwo[i]){
merged[i+i] = mergeOne[i];
merged[i+i+1] = mergeTwo[i];
}
else if(mergeTwo[i]<=mergeOne[i]){
merged[i+i] = mergeTwo[i];
merged[i+i+1]= mergeOne[i];
}
}
}
if(mergeOne.length<mergeTwo.length){
for(int k=lengthShort; k<lengthLong; k++){
merged[k]=mergeTwo[k];
}
}
if(mergeOne.length>mergeTwo.length){
for(int k=lengthShort; k<lengthLong; k++){
merged[k]=mergeOne[k];
}
}
for(int i = 0; i<merged.length; i++){
if((i+1)==merged.length)
break;
if(merged[i]>merged[i+1]){
int temp = merged[i+1];
merged[i+1]=merged[i];
merged[i]= temp;
}
}
System.out.println("\nMerged array in order is: ");
for(int i = 0; i<merged.length; i++){
System.out.print(merged[i] + " ");
}
}
}
//My code compiles in drjava but I have two issues:
1) It doesn't order the numbers in ascending order
2) When I run it through the site I have to submit this on it gives me the message as follows:
Runtime Error
Exception in thread "main" java.lang.NegativeArraySizeException
at Main.main(Main.java:281)
at Ideone.assertRegex(Main.java:94)
at Ideone.test(Main.java:42)
at Ideone.main(Main.java:29)
You'll need to rethink your merge algorithm. Suppose you input arrays are
1 5 10 50 100 500
2 4 6 8 10 12 14 16
You'll need to repeatedly decide which element is smaller to put into the output. So after selecting N elements, your output will look like
1 2 4 5 6 8 10 10 12 14
And you will need to have indexes pointing at the place in the input arrays you'll need to look at next:
1 5 10 50 100 500
^^
2 4 6 8 10 12 14 16
^^
As you can see, the indexes could be at very different places in the input arrays. However, your code does a lot of this:
if(mergeOne[i]<=mergeTwo[i]){
which means it's only comparing elements from the input that are in the same location. This doesn't work, and trying to swap elements in the output after the fact isn't good enough to get the job done.
Basically, instead of having one index and comparing the elements of the two input arrays at the same index, you'll need two indexes. I'll let you take it from there, but I think you can figure it out.
(And I have no idea why you're getting NegativeArraySizeException.)