I am new to java and array lists. I am supposed to sort populate an array full of random integers, then if there is a run (multiples of the same number in a row), put ( ) around that run.
So if the random list is:
2 3 4 5 5 5 5 6 7 7 9
2 3 4 (5 5 5 5) 6 (7 7) 9
This is what I have so far:
import java.util.*;
class Run {
public static void main (String [] args){
Scanner m = new Scanner(System.in);
System.out.print("Enter length wanted: ");
int len = m.nextInt();
System.out.print("Enter max number wanted: ");
int max = m.nextInt();
max = max -1;
int[] x = new int[len];
ArrayList<String> y = new ArrayList<String>();
//Filling x with random numbers
for(int i = 0; i<len; i++){
x[i] = ((int)(Math.random()*max)+1);
}
System.out.println("Orginal Array: " + Arrays.toString(x));
for(int i = 0; i<=len-1; i++){
if(x[i] == x[i++]){ //I just don't know how I am exactly supposed to sort this
}else{
}
}
//Array List with ()
System.out.println("Runs labeled Array: " + y);
}
}
You're going to need a String to display the final output. Also, don't go out of the array.
Try Something like this:
x = Collections.sort(x);
String s = "";
boolean b;
for(int i = 0; i<=len-1; i++){
if(x[i] == x[i+1]){
s+=" ("+i+" ";
b = true;
}else{
if(b == true){
s+=i+") ";
b = false;
}
s+=i + " ";
}
}
use Collections.sort(yourList) to sort your ArrayList.
If you dont wanna use API methods.
try :
for(int i=0;i<list.size(); i++){
for(int j=i+1; j<list.size(); j++){
if(list.get(i)>list.get(j)){
temp = list.get(i);
list.set(i,list.get(j));
list.set(j, temp);
}
}
}
Related
// Repetaded element run multiple times means avoid duplicate element count multiple times
import java.util.Scanner;
public class FindFrequency {
public static void main(String[] args) {
int t, count=0;
Scanner in = new Scanner(System.in);
System.out.println("Enter number of elements to insert in an array: ");
int len = in.nextInt();
int[] arr = new int[len];
System.out.println("Enter elements to insert in an array: ");
for( int i=0;i<len;i++)
{
t = in.nextInt();
arr[i] = t;
}
System.out.println("\n");
for(int i=0;i<len;i++)
{
count=1;
for(int j=i+1;j<=len-1;j++)
{
if(arr[i]==arr[j] )
{
count++;
}
}
System.out.println(arr[i] + " is " + count + " times.\n");
}
}
}
I have used one more array to store the print value.We can use set as well as.I hope you get the answer.
let array = [1,2,1,3,4,5,6,2]
var arrayWithPosition = [Int]()
for i in 0..<array.count {
var position = 0
while position < arrayWithPosition.count {
if arrayWithPosition[position] == array[i]{
break
}
position += 1
}
if position == arrayWithPosition.count{
arrayWithPosition.append(array[i])
}else{
continue
}
var count = 1
for j in i+1..<array.count {
if array[i] == array[j] {
count += 1
}
}
print(array[i],count)
}
Output : -
1 2
2 2
3 1
4 1
5 1
6 1
This is the output i need (
Input Array: 1 2 3 4 5 6 7
Random Output: 7 2 3 6 1 5 4)
this is what i get
Input size of the Array
5
Input Value
1
Input Value
2
Input Value
3
Input Value
4
Input Value
5
Random Output: 2
Random Output: 0
Random Output: 0
Random Output: 0
Random Output: 0
The problem is with line 23 and im not sure how to fix it
import java.util.Random;
import java.util.Scanner;
public class problem_2 {
public static void main(String args[]){
Random r = new Random();
Scanner m = new Scanner(System.in);
System.out.println("Input size of the Array");
int size = m.nextInt();
int a[] = new int[size];
int b[] = new int[size];
for(int i = 0;i<a.length;i++) {
System.out.println("Input Value " +(i+1));
a[i] = m.nextInt();
}
int cell = 0;
int x = r.nextInt(size);
int value = a[x];
while(cell<size) {
for(int i =0; i<= size;i++) {
if (b[i]==value) {
cell++;
}
if(cell==0) {
b[cell] = value;
cell++;
}
System.out.println("Random Output: "+b[i]);
}
}
}
}
The problem is your code is going one too many indexes in the following for loop:
for(int i =0; i<= size;i++)
That's because you have to remember an array with say 5 elements has indexes 0-4. So while the size is the number of elements in the array the largest index is always (the number of elements) - 1.
So you should write the for loop like so:
for(int i = 0; i < size;i++)
Even then your code doesn't quite randomize correctly. The easiest way to randomize an array would be to swap out each element with another random element, like this:
//Randomize the array
for(int i = 0; i < size;i++) {
//lets get a random index in the array
int randIndex = (int)(Math.random()*size);
//then we will store the index we are swapping because its going to be overwritten
int temp = a[i];
//set our index equal to the random one
a[i] = a[randIndex];
//put our index's original value into the random index, so its not lost
a[randIndex] = temp;
}
thanks everyone for the help but i didnt learn any of the things in the others so
i found a easier way to do it
import java.util.Random;
import java.util.Scanner;
public class random{
public static void main(String args[]){
Random r = new Random();
Scanner m = new Scanner(System.in);
System.out.println("Input size of the Array");
int size = m.nextInt();
int a[] = new int[size];
int b[] = new int[size];
for(int i = 0;i<a.length;i++) {
System.out.println("Input Value ");
a[i] = m.nextInt();
}
int cell = 0;
while(cell<size) {
int n = r.nextInt(size);
int value = a[n];
int count = 0;
for(int i =0; i< size;i++) {
if (b[i]== value) {
count++;
}
}
if(count==0) {
b[cell] = value;
cell++;
}
}
System.out.println ("\n");
System.out.println("Input Array: ");
for (int i = 0; i<size; i++){
System.out.print(a[i] + " ");
}
System.out.println ("\n");
System.out.println("Random Output: ");
for (int i = 0; i<size; i++){
System.out.print(b[i] + " ");
}
}
}
What I need to do is ask the user to input values for two arrays and then output them separately and also output a merged array that is in ascending order.
For example, if the user inputs 2,5,8,0 for the first array and 6,7,0 for the second array, then the merged array should output 2,5,6,7,8.
The output for my first two arrays work perfectly but the merged array always outputs a zero. I also added a restart boolean to see if the user wants to try it again. Please help me as I am stuck.
I understand the though process but not sure how to implement this into my code. Here is my code:
//import packages
import java.util.Scanner;
import java.lang.Math;
import java.util.Arrays;
public class Main4{
public static void main(String[] args){
boolean doItAgain = true;//add boolean value to use when restarting progam
Scanner scan = new Scanner (System.in);//initialize new scanner
while(doItAgain){
//initialize variables
int first [] = new int[10000];//initialize to maximum of 10,000 integers
int second [] = new int[10000];//initialize to maximum of 10,000 integers
int input1;
int input2;
int counter1 = 0;//counter variable for first string
int counter2 = 0;//counter variable for second string
System.out.println("");
System.out.println("Welcome To my Merge Array Program 2.0!");
System.out.println("Enter the values for the first array, up to 10000 values, enter zero or a negative number to quit"); //asks user for first array input
//loop to go through each index
for (int a = 0; a<10000; a++)
{
input1 = scan.nextInt();//stores input as input1
first [a] = input1;
counter1++;
if (input1<=0)
break;//breaks out of loop if input1 value is 0 or below
}
int first2 []= new int [counter1-1];
for(int b = 0; b<first2.length; b++) {
first2 [b] = first[b];
}
System.out.println("Enter the values for the second array, up to 10000 values, enter zero or a negative number to quit"); //asks user for second array input
for (int j = 0; j<10000; j++)
{
input2 = scan.nextInt();//stores input as input2
second [j] = input2;
counter2++;
if (input2<=0)
break;//breaks out of loop if input1 value is 0 or below
}
int second2 []= new int [counter2-1];
for(int c = 0; c<second2.length; c++) {
second2 [c] = second[c];
}
System.out.println("First Array:");//output first array values in the order of their input
for (int p=0; p<first2.length; p++) {
System.out.print(first2[p] + " ");
}
System.out.println("\nSecond Array:");//output second array values in the order of their input
for (int p2=0; p2<second2.length;p2++) {
System.out.print(second2[p2] + " ");
}
boolean valid = true;
for (int e = 0; e<first2.length-1; e++) {
if(first2[e]>first2[e+1]) {
valid = false;
}
}
for (int e2 = 0; e2<second2.length-1;e2++) {
if(second2[e2]>second2[e2+1]) {
valid = false;
}
}
int[] array = new int[first2.length + second2.length];
//fill array 3 with arrays 1 & 2
for(int k = 0; k <first2.length;k++){
array[k] = first2[k];
}
for (int l = 0; l<second2.length; l++){
array[first2.length + l] = second2[l];
}
//sort array 3
for (int i = 0; i<first2.length + 1; i++){
for (int j = i+1; j<first2.length + 1; j++){
if(array[i] > array[j]){
int temp = array[i];
array[i] = array[j];
array[j] = temp;
}
}
}
//output sorted merged array
System.out.println("\nMerged Array: ");
for(int p3 = 0; p3<array.length; p3++) {
System.out.print(array[p3] + " ");
}
//Asks user if they want to restart program. Used boolean value to initialize doItAgain variable
System.out.println("");
System.out.println("");
System.out.println("Thanks for using this program! Do you want to do it again? (Y or N)");
if(scan.next().toLowerCase().equals("y")){
doItAgain = true;
break;
}
else{
doItAgain = false;
System.out.println("If you change your mind and want to run it again, type runMain.");//output closing statement if user says N to restart
break;
}
}
}
}
You are not merging your arrays. Your 1st array is, for instance [1 2] and your second array is, for instance [3 4]. Your final array is going to be initialized with size 4 (first2.length + second2.length), but all it's elements will be zero.
In this line here, I suggest you use arraycopy() to fill your final array:
int[] array = new int[first2.length + second2.length];
System.arraycopy(first2, 0, array, 0, first2.length);
System.arraycopy(second2, 0, array, first2.length, second2.length);
This will copy the first2 array to the starting position of your final array and then copy your second2 array to the position of your final array where first2 ended. You will end up with [1 2 3 4] and can then sort the elements (though in this case, they're already sorted.
For more information on arraycopy() consult this page here:
https://www.tutorialspoint.com/java/lang/system_arraycopy.htm
EDIT: BTW, you have an error right here, which is what is preventing you from printing the full sorted array:
//output sorted merged array
System.out.println("\nMerged Array: ");
for(int p3 = 0; p3<array.length; p3++) {
System.out.print(array[p3] + " ");
} //right here, you need to close this curly bracket
EDIT2: Since you can't use arraycopy(), you can use for loops to fill in the final array:
for(int k = 0; k <first2.length;k++){
array[k] = first2[k];
}
for (int l = 0; l<second2.length;l++){
array[first2.length + l] = second2[l];
}
I am trying to list all the content in a text file then calculate the number of each element by ignoring the first element in each row and sort it in descending order. I don't know how can i sort it.
The content of the text file :
1,2,8,4,5,6,7,7,
3,4,5,6,7,8,3,
5,6,7,8,9,9,
I want the expected result to like this :
Exam[1] : 2 8 4 5 6 7 7
count : 7
Exam[3] : 4 5 6 7 8
count : 5
Exam[5] : 6 7 8 9 9 3
count : 6
Sorted :
How can i sort count 7, count 6 and count 5 in descending order ?
I have tried using this sorting :
private static void sortInDescending(int[] num){
int n = num.length;
int temp = 0;
for(int i = 0; i < n; i++) {
for(int j = 1; j < (n-i); j++) {
temp = num[j-1];
num[j-1] = num[j];
num[j] = temp;
}
}
}
But this sort is to sort each element in each row in descending order.
This is my coding that i done so far :
Scanner scanner = new Scanner(new File("test.txt"));
int row = 0;
int count = 0;
while(scanner.hasNextLine()) {
String currentline = scanner.nextLine();
row++;
String[] items = currentline.split(",");
int[] intitems = new int[items.length];
int i = 0;
for(i = 0; i < items.length; i++) {
intitems[i] = Integer.parseInt(items[i]);
if(i == 0) {
System.out.print("Exam[" +intitems[i]+ "] ");
} else {
System.out.print(intitems[i]+ " ");
count++;
}
}
System.out.println("\nCount " +count);
count = 0;
}
Here is how you can sort your arrays instead of doing it yourself using Arrays
//initialize the array which you want to sort
//in your case it would be `exam` or `count` array
//Pass the array as an argument to sort method, for example
int[] s = new int[10]; //initialize it with values
Arrays.sort(s); //this will sort it in ascending order
System.out.println(Arrays.toString(s)); //to print it
Now, if you want to reverse it - use a for loop and read your array from last index to first index. I am sure you can make that.
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.