public class AssignmentChapter8
{
public static void main(String[] args)
{
int randomNumbers = new int[100];
int counter = 0;
while(counter < randomNumbers.length)
{
randomNumbers[counter] = (int)(Math.random() * 25);
counter++;
}
int oddNumbers[] = new int[100];
oddNumbers[] = getOddNumbers(randomNumbers);
int evenNumbers[] = new int[100];
evenNumbers[] = getEvenNumbers(randomNumbers);
System.out.println("The odd numbers are:");
for(int k = 0; k < oddNumbers.length; k++)
System.out.print("\t" + oddNumbers[k]);
System.out.println("The even numbers are:");
for(int l = 0; l < evenNumbers.length; l++)
System.out.print("\t" + evenNumbers[l]);
}
public static int getOddNumbers(int randomNumbers)
{
int oddNumbers[] = new int[100];
int counterA = 0;
int counterB = 0;
int counter = 0;
int placeholder;
while(counter < randomNumbers.length)
{
if(randomNumbers[counterA] % 2 > 0)
{
oddNumbers[counterB] = randomNumbers[counterA];
counterB++;
}
counterA++;
counter++;
}
return oddNumbers;
}
public static int getEvenNumbers(int randomNumbers)
{
int evenNumbers[] = new int[100];
int counterA = 0;
int counterB = 0;
int counter = 0;
int placeholder;
while(counter < randomNumbers.length)
{
if(randomNumbers[counterA] % 2 > 0)
{
evenNumbers[counterB] = randomNumbers[counterA];
counterB++;
}
counterA++;
counter++;
}
return evenNumbers;
}
}
I have been trying to execute a program to sort variables in arrays, but I keep getting a ';' expected error in the line after declaration of the array where the program is supposed to retrieve an array from a function. Any help would be appreciated.
This is bad syntax (which causes the ';' expected error ):
oddNumbers[] = getOddNumbers(randomNumbers);
The brackets are not needed. You can do this:
oddNumbers = getOddNumbers(randomNumbers);
Besides that, you have plenty of errors:
int randomNumbers[] = new int[100]; // you need the brackets
Your return value in the method declaration is wrong (you are returning an array, not an int):
public static int[] getEvenNumbers(int randomNumbers)
int oddNumbers[] = new int[100];
By initializing oddNumbers become an array. when you want to assign values,
oddNumbers={elements of array}
Both left and right hand side both should arrays.
May be you should use IDE for coding then it may help you to understand some issues like this.
Related
I got some problem someone of with really helped me but I got program source code who print all of divisor from array, but I tried to print a number with most divisor for ex. array[1,2,3,4,5] and I want to print that the number with most divisor is 4 (1,2,4)
public static class Main {
public static void main(String[] args) {
System.out.println(getNumWithMaxDivisors(numbers));
}
static int getNumDivisors(int n) {
int noOfDivisors = 0;
for (int i = 1; i <= n / 2; i++) {
if (n % i == 0) {
System.out.print(i + " ");
noOfDivisors++;
}
}
return noOfDivisors;
}
static int getNumWithMaxDivisors(int[] numbers) {
int currentMaxDivisors = 0;
int numWithMaxDivisors = numbers[0];
for (int i = 0; i < numbers.length; i++) {
int numDivisors = getNumDivisors(numbers[i]);
if (numDivisors > currentMaxDivisors) {
numWithMaxDivisors = numbers[i];
}
}
return numWithMaxDivisors;
}
}
Code looks that, do you know where is a problem ?
The problem is that inside of your getNumWithMaxDivisors() method, you are not redefining the current number of max divisors. To fix this, you can update it inside of the if statement as so:
static int getNumWithMaxDivisors(int[] numbers) {
int currentMaxDivisors = 0;
int numWithMaxDivisors = numbers[0];
for (int i = 0; i < numbers.length; i++) {
int numDivisors = getNumDivisors(numbers[i]);
if (numDivisors > currentMaxDivisors) {
currentMaxDivisors = numDivisors; //ADD THIS LINE
numWithMaxDivisors = numbers[i];
}
}
return numWithMaxDivisors;
}
Input:
int[] numbers = {1,2,3,4,5};
System.out.println(getNumWithMaxDivisors(numbers));
Output:
4
Side Note: You could just as well start your for loop at i = 2 in your getNumDivisors() method, since every number is divisible by 1, so there is no point in checking it. This just saves you a bit of time!
add this line of code currentMaxDivisors = numDivisors; inside your if-statement like so:
static int getNumWithMaxDivisors(int[] numbers) {
int currentMaxDivisors = 0;
int numWithMaxDivisors = numbers[0];
for (int i = 0; i < numbers.length; i++) {
int numDivisors = getNumDivisors(numbers[i]);
if (numDivisors > currentMaxDivisors) {
currentMaxDivisors = numDivisors; //here this is missing
numWithMaxDivisors = numbers[i];
}
}
return numWithMaxDivisors;
}
How can i create a random number a specific numbers of time?
public class Feld {
public static void main(String[] args) {
double k = (int)(Math.random()*1000001);
int n = 1000000;
int arr[] = new int[n];
int i = 0;
for(i = 0;i<n;i++){
arr[i] = i;
}
boolean found = false;
i=0;
while (i < arr.length) {
if (arr[i] == k) {
found = true;
break;
}
i++;
}
if (found) {
i++;
System.out.println(i);
}
else {
System.out.println((arr.length + 1));
}
}
}
My problem is, that if i put k into a loop to create it more than one time i'll get an error at:
if (arr[i] == k)
!!I just found out that i made a mistake explaining my problem. The array should be filled with values from 0-1.000.000 and i am supposed to print out the position of a random generated number for a specific amount of times.
If you want to have an array full of random numbers, I suggest using the following:
int n = 1000000;
int arr[] = new int[n];
for(int i = 0; i < n; i++){
arr[i] = (int)(Math.random() * 1000001);
}
That will work and you don't even need the variable k.
Edit:
If you want to print at what position you find a specific value (for example x = 543), you can use the following code:
int x = 543;
int n = 1000000;
int arr[] = new int[n];
for(int i = 0; i < n; i++){
arr[i] = (int)(Math.random() * 1000001);
if(arr[i] == x) {
System.out.println(i);
break;
}
}
Edit2
One possible solution to your new problem looks like this:
public class Feld {
public static void main(String[] args) {
int n = 1000000;
int arr[] = new int[n];
int i = 0;
for(i = 0; i < n; i++){
arr[i] = i; //Filling array with values 0-1000000
}
int number = 20; //Print out position of a random generated number a specific amount of times
int randomNumber = (int)(Math.random()*1000001); //The random number
for(int j = 0; j < number; j++) { //Find number for a specific amount of times
for(int k = 0; k < arr.length; k++) { //Find number in array
if(arr[k] == randomNumber) {
System.out.println(arr[k]); //Print
break; //Number found, don't have to search anymore
}
}
}
}
}
I would write a method that returns an array of random numbers and takes an int argument that defines the length of the array.
One possible solution is this:
public static int[] createRandomArray(int length) {
// create an array of the given length
int[] result = new int[length];
// and use a single for loop that puts random int values into every index
for (int i = 0; i < result.length; i++) {
result[i] = ThreadLocalRandom.current().nextInt();
}
// then simply return the result
return result;
}
Try it as follows
public static void main(String[] args) {
// super primitive time measurement:
// take the moment in time before calling the method
Instant start = Instant.now();
// then call the method
int[] array = createRandomArray(1000000);
// and take the moment in time after the method returned
Instant end = Instant.now();
// then calculate the duration
Duration duration = Duration.between(start, end);
// and print the duration in milliseconds
System.out.printf("Array creation took %d milliseconds\n", duration.toMillis());
}
The result is the following output on my system:
Array creation took 10 milliseconds
my intend is to use simplest java (array and loops) to generate random numbers without duplicate...but the output turns out to be 10 repeating numbers, and I cannot figure out why.
Here is my code:
int[] number = new int[10];
int count = 0;
int num;
while (count < number.length) {
num = r.nextInt(21);
boolean repeat = false;
do {
for (int i=0; i<number.length; i++) {
if (num == number[i]) {
repeat = true;
} else if (num != number[i] && i == count) {
number[count] = num;
count++;
repeat = true;
}
}
} while (!repeat);
}
for (int j = 0; j < number.length; j++) {
System.out.print(number[j] + " ");
}
How about you use a Set instead? If you also want to keep track of the order of insertion you can use a LinkedHashSet.
Random r = new Random();
Set<Integer> uniqueNumbers = new HashSet<>();
while (uniqueNumbers.size()<10){
uniqueNumbers.add(r.nextInt(21));
}
for (Integer i : uniqueNumbers){
System.out.print(i+" ");
}
A Set in java is like an Array or an ArrayList except it handles duplicates for you. It will only add the Integer to the set if it doesn't already exist in the set. The class Set has similar methods to the Array that you can utilize. For example Set.size() is equivalent to the Array.length and Set.add(Integer) is semi-equivalent to Array[index] = value. Sets do not keep track of insertion order so they do not have an index. It is a very powerful tool in Java once you learn about it. ;)
Hope this helps!
You need to break out of the for loop if either of the conditions are met.
int[] number = new int[10];
int count=0;
int num;
Random r = new Random();
while(count<number.length){
num = r.nextInt(21);
boolean repeat=false;
do{
for(int i=0; i<number.length; i++){
if(num==number[i]){
repeat=true;
break;
}
else if(i==count){
number[count]=num;
count++;
repeat=true;
break;
}
}
}while(!repeat);
}
for(int j=0;j<number.length;j++){
System.out.print(number[j]+" ");
}
This will make YOUR code work but #gonzo proposed a better solution.
Your code will break the while loop under the condition: num == number[i].
This means that if the pseudo-generated number is equal to that positions value (the default int in java is 0), then the code will end execution.
On the second conditional, the expression num != number[i] is always true (otherwise the code would have entered the previous if), but, on the first run, when i == count (or i=0, and count=0) the repeat=true breaks the loop, and nothing else would happen, rendering the output something such as
0 0 0 0 0 0...
Try this:
int[] number = new int[10];
java.util.Random r = new java.util.Random();
for(int i=0; i<number.length; i++){
boolean repeat=false;
do{
repeat=false;
int num = r.nextInt(21);
for(int j=0; j<number.length; j++){
if(number[j]==num){
repeat=true;
}
}
if(!repeat) number[i]=num;
}while(repeat);
}
for (int k = 0; k < number.length; k++) {
System.out.print(number[k] + " ");
}
System.out.println();
Test it here.
I believe the problem is much easier to solve. You could use a List to check if the number has been generated or not (uniqueness). Here is a working block of code.
int count=0;
int num;
Random r = new Random();
List<Integer> numbers = new ArrayList<Integer>();
while (count<10) {
num = r.nextInt(21);
if(!numbers.contains(num) ) {
numbers.add(num);
count++;
}
}
for(int j=0;j<10;j++){
System.out.print(numbers.get(j)+" ");
}
}
Let's start with the most simple approach, putting 10 random - potentially duplicated - numbers into an array:
public class NonUniqueRandoms
{
public static void main(String[] args)
{
int[] number = new int[10];
int count = 0;
while (count < number.length) {
// Use ThreadLocalRandom so this is a contained compilable unit
number[count++] = ThreadLocalRandom.current().nextInt(21);
}
for (int j = 0; j < number.length; j++) {
System.out.println(number[j]);
}
}
}
So that gets you most of the way there, the only thing you know have to do is pick a number and check your array:
public class UniqueRandoms
{
public static void main(String[] args)
{
int[] number = new int[10];
int count = 0;
while (count < number.length) {
// Use ThreadLocalRandom so this is a contained compilable unit
int candidate = ThreadLocalRandom.current().nextInt(21);
// Is candidate in our array already?
boolean exists = false;
for (int i = 0; i < count; i++) {
if (number[i] == candidate) {
exists = true;
break;
}
}
// We didn't find it, so we're good to add it to the array
if (!exists) {
number[count++] = candidate;
}
}
for (int j = 0; j < number.length; j++) {
System.out.println(number[j]);
}
}
}
The problem is with your inner 'for' loop. Once the program finds a unique integer, it adds the integer to the array and then increments the count. On the next loop iteration, the new integer will be added again because (num != number[i] && i == count), eventually filling up the array with the same integer. The for loop needs to exit after adding the unique integer the first time.
But if we look at the construction more deeply, we see that the inner for loop is entirely unnecessary.
See the code below.
import java.util.*;
public class RandomDemo {
public static void main( String args[] ){
// create random object
Random r = new Random();
int[] number = new int[10];
int count = 0;
int num;
while (count < number.length) {
num = r.nextInt(21);
boolean repeat = false;
int i=0;
do {
if (num == number[i]) {
repeat = true;
} else if (num != number[i] && i == count) {
number[count] = num;
count++;
repeat = true;
}
i++;
} while (!repeat && i < number.length);
}
for (int j = 0; j < number.length; j++) {
System.out.print(number[j] + " ");
}
}
}
This would be my approach.
import java.util.Random;
public class uniquerandom {
public static void main(String[] args) {
Random rnd = new Random();
int qask[]=new int[10];
int it,i,t=0,in,flag;
for(it=0;;it++)
{
i=rnd.nextInt(11);
flag=0;
for(in=0;in<qask.length;in++)
{
if(i==qask[in])
{
flag=1;
break;
}
}
if(flag!=1)
{
qask[t++]=i;
}
if(t==10)
break;
}
for(it=0;it<qask.length;it++)
System.out.println(qask[it]);
}}
public String pickStringElement(ArrayList list, int... howMany) {
int counter = howMany.length > 0 ? howMany[0] : 1;
String returnString = "";
ArrayList previousVal = new ArrayList()
for (int i = 1; i <= counter; i++) {
Random rand = new Random()
for(int j=1; j <=list.size(); j++){
int newRand = rand.nextInt(list.size())
if (!previousVal.contains(newRand)){
previousVal.add(newRand)
returnString = returnString + (i>1 ? ", " + list.get(newRand) :list.get(newRand))
break
}
}
}
return returnString;
}
Create simple method and call it where you require-
private List<Integer> q_list = new ArrayList<>(); //declare list integer type
private void checkList(int size)
{
position = getRandom(list.size()); //generating random value less than size
if(q_list.contains(position)) { // check if list contains position
checkList(size); /// if it contains call checkList method again
}
else
{
q_list.add(position); // else add the position in the list
playAnimation(tv_questions, 0, list.get(position).getQuestion()); // task you want to perform after getting value
}
}
for getting random value this method is being called-
public static int getRandom(int max){
return (int) (Math.random()*max);
}
For school, i have to build myself a method in java that compresses an array using RLE(run-length encoding). I can't find a solution online because my teacher wants me to solve the problem myself. I, unfortunately, cannot do this for i am a busy man with some busy plans.
RLE turns this: {1,1,1,1,2,2,3,3,6,6,6,7,8,8,8}
into this: {4,1,2,2,2,3,3,6,1,7,3,8}
it basically makes a new array that follows this formula {# of this value, this value, # of this value, this value, cont...} there are 4 1's so {4,1} you get my drift.
Here is what i tried to do(forgive me for my crappy code, i am merely a high school student):
public class tester{
public static void main(String[] args){
int[] potato = {1,1,1,2,2,4,4,4,6,6,6,6};
printArray(compress(potato));
}
public static void printArray(int[] arr){
for(int i = 0; i < arr.length; i++){
System.out.println(arr[i]);
}
}
public static int[] compress(int[] a) {
//figure out how many different numbers there are.
int diffNums = 1;
for(int i = 0; i < a.length; i++){
if(i != a.length-1 && a[i] != a[i+1]){
diffNums++;
}
}
//make compressed array at the correct length.
int[] compressed = new int[diffNums * 2];
//figure out what each number is.
int[] nums = new int[diffNums];
nums[0] = a[0];
int spot = 0;
for(int i = 0; i < a.length; i++){
if(i != a.length-1 && a[i] != a[i+1]){
nums[spot] = a[i+1];
}
}
//figure out quantity of each number.
int[] quantities = new int[diffNums];
int spot2 = 0;
int spotcur = 0;
for(int i = 0; i < diffNums; i++){
int quant = 0;
while(a[spotcur] == a[spot2]){
quant++;
spotcur++;
}
spot2 = spotcur;
quantities[i] = quant;
}
//add them together and return compressed array
int spotter = 0;
for(int i = 0; i < diffNums; i++){
compressed[spotter] = quantities[i];
spotter++;
compressed[spotter] = nums[i];
spotter++;
}
return compressed;
}
}
Does anyone know how i can fix this crappy code? i am stuck on it
I think this problem could be solved with a lot less code. You could use an outer/inner loop construct something like the following:
public static int[] compress(int[] a) {
List<Integer> encoded = new ArrayList<>();
for (int i=0; i<a.length; i++) {
int num = a[i];
int count = 1;
for (int j=i+1; j<a.length; j++) {
int nextNum = a[j];
if (nextNum != num)
break;
count++;
i++;
}
encoded.add(count);
encoded.add(num);
}
return encoded.stream().mapToInt(i->i).toArray();
}
Also, the Arrays class contains a useful toString method already defined.
System.out.println(Arrays.toString(compress(potato)));
I have to make a 3 way merge sort of an array. the array length is a in a power of 3, i.e. 3,9,27 etc. So I can use only one split function and not "left","mid","right".
Would like to get an answer how to repair it and why does not it work.
I have written the code, however don't know how to get it to work.
Here it is:
EDITED THE CODE, STILL DOES NOT WORK
public class Ex3 {
public static void main(String[] args) { //main function
Scanner in = new Scanner(System.in); //scanner
int size = in.nextInt();
int[] arr = new int[size];
for (int i = 0; i<arr.length; i++){
arr[i] = in.nextInt();
}
in.close();
arr = merge3sort (arr); //send to the function to merge
for (int i = 0; i<arr.length; i++){ //printer
System.out.print(arr[i]+ " ");
}
}
static int[] split(int[] m, int thirdNum) { //split function that splits to 3 arrays
int third[] = new int[m.length/3];
int third1[]=new int[m.length/3];
int third2[]=new int[m.length/3];
for(int i = 0; i<=m.length/3; i++)
third[i]=m[i];
for(int i=0; i<=m.length/3;i++)
third1[i]=m[i+thirdNum];
for(int i=0; i<=m.length/3;i++)
third2[i]=m[i+2*thirdNum];
return merge(third,third1,third2);
//return null;
}
static int minOf3(int[] a3) { //function that finds out how what is the index of the smallest number
int num0 = a3[0];
int num1 = a3[1];
int num2 = a3[2];
int idx = 0;
if(num0<num1 && num1<num2)
idx=0;
if(num1<num0 && num0<num2)
idx=1;
else
idx=2;
return idx;
}
static int[] merge(int[] th0, int[] th1, int[] th2) { //function that sorts the numbers between 3 arrays
int len0=th0.length;
int len1=th1.length;
int len2=th2.length;
int[] united = new int[len0+len1+len2];
int ind = 0; int i0=0; int i1=0; int i2=0;
while(i0<len0 && i1<len1 && i2<len2){
if(th0[i0]<th1[i1]){
if(th0[i0]<th2[i2]){
united[ind]=th0[i0];
i0=i0+1;
}//end inner if
else{
united[ind]=th2[i2];
i2=i2+1;
}//end inner else
}//end outer if
else{
united[ind]=th1[i1];
i1=i1+1;
}//end outer else
ind=ind+1;
}//end while
for (int i = i0; i < len0; i = i + 1) {
united[ind] = th0[i];
ind = ind + 1;
}
for (int i = i1; i < len1; i = i + 1) {
united[ind] = th1[i];
ind = ind + 1;
}for (int i = i2; i < len2; i = i + 1) {
united[ind] = th2[i];
ind = ind + 1;
}
return united;
}
static int[] merge3sort(int[] m) { //function that glues all together
if (m.length == 1) {
return m;
}
else{
return merge(merge3sort(split(m,m.length/3)),merge3sort(split(m,m.length/3)),merge3sort(split(m,m.length/3))); }
}
I get the following exception:
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 0
at ololosh1.Ex3.split(Ex3.java:27)
at ololosh1.Ex3.merge3sort(Ex3.java:98)
at ololosh1.Ex3.main(Ex3.java:15)
Look at this part of your code:
for(int i = 0; i<=m.length/3; i++)
third[i]=m[i];
for(int i=0; i<=m.length/3;i++)
third1[i]=m[i+thirdNum];
for(int i=0; i<=m.length/3;i++)
third2[i]=m[i+2*thirdNum];
Arrays are indexed from 0 to length-1. Each third* array has length m.length/3. Therefore their index can only go up to m.length/3 - 1. Yet you are indexing up to and including m.length/3.
Once you get your application working correctly, you really should clean it up. There is a lot of redundancy. For example, you are using the expression m.length/3 multiple times in method split() but you are also passing that same value to it as an argument.