I am getting an error when making the call to method findPosition. What I'm trying to do with the program is measure how long the algorithm runs on average, over 1000 iterations of it. Then I want to call the method and find the position of the value (if it is found) in the array. I'm getting a compiler error that the arguments being passed do not match the method. Specifically, the second argument is being taken as an int, even though I want to pass the value in an array. I can't find my error and am new to working with arrays, so thank you in advance if you can tell me where my mistake is.
import java.util.*;
public class AlgorithmRuntime
{
static int num = 0;
static long total = 0;
static long average = 0;
public static void main (String[] args)
{
boolean isValueInArray;
int searchValue;
do {
// 1. Setup
int size = 1000;
long sum = 0;
int[] iArray = new int[size];
Random rand = new Random(System.currentTimeMillis());
for (int i = 0; i < size; i++)
iArray[i] = rand.nextInt();
searchValue = rand.nextInt(1000) + 1;
// 2. Start time
long start = System.nanoTime();
// 3. Execute algorithm
for (int j = 0; j < size; j++)
{
if (iArray[j] == searchValue)
{
isValueInArray = true;
}
if (isValueInArray == true)
findPosition(searchValue, iArray[isValueInArray]);
}
// 4. Stop time
long stop = System.nanoTime();
long timeElapsed = stop - start;
total = total + timeElapsed;
num++;
} while (num < 1000);
average = total / 1000;
System.out.println("The algorithm took " + average
+ " nanoseconds on average to complete.");
}
}
public int findPosition(int valueOfInt, int[] array)
{
for (int i = 0; i < array.length; i++)
if (array[i] == valueOfInt)
return i;
return -1;
}
findPostion method accepts two arguments; one of type int and another of type int array. Here is the signature of findPosition:
public int findPosition(int valueOfInt, int[] array)
but you are passing it two int values as mentioned here:
findPosition(searchValue, iArray[isValueInArray];
isArray is an int array but iArray[isValueInArray] is an int value at index isValueInArray.
You need to pass an array as the second param instead of an int value.
You need to pass in
if (isValueInArray == true) {
findPosition(searchValue, iArray);
}
iArray[isValueInArray] will give you an int value and not the array.
Related
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
I have a problem to convert from int to int []. I have tried to modify the coding but still have error. I want to change the method getRandomNumberInRange into int[] because i need to combine with [hostType] and [hostType] is in array form.
// this method is to convert from int to int[]
static Integer[] toObject(int[] intArray) {
Integer[] result = new Integer[intArray.length];
for (int i = 0; i < intArray.length; i++) {
result[i] = Integer.valueOf(intArray[i]);
}
return result;
}
// this method to generate random number
public static int getRandomNumberInRange(int min, int max) {
if (min >= max) {
throw new IllegalArgumentException("max must be greater than min");
}
Random r = new Random();
return r.nextInt((max - min) + 1) + min;
}
//this method is to implement the function getRandomNumberInRange and need to be in array form
public static List<PowerHost> createHostList(int hostsNumber) {
List<PowerHost> hostList = new ArrayList<PowerHost>();
for (int i = 0; i < hostsNumber; i++) {
int hostType = i % Constants.HOST_TYPES;
// int mips2[]=(int) getRandomNumberInRange(100, 1000);
List<Pe> peList = new ArrayList<Pe>();
for (int j = 0; j < Constants.HOST_PES[hostType]; j++) {
int[] obj = new int[hostType] ;
Integer[] newObj = toObject(obj);
peList.add(new Pe(j, new PeProvisionerSimple(getRandomNumberInRange(100, 1000)[newObj])));
}
There are a few things wrong. First, in the last code snippet, you are missing two '}'s. Second, getRandomNumberInRange(int min, int max) returns an int, which is not an array. What that means is that you wouldn't do getRandomNumberInRange(100, 1000)[newObj] because that is like doing 107[4]. 107 isn't an array so that wouldn't work. Also, newObj is an array, so even if getRandomNumberInRange returned an array, newObj wouldn't be able to be used as an index to get the int in the array. This is because the index (the thing that goes in array[here]) must be an int.
What is wrong with my code? My output has to be the sum of all long elements in the second row of 'ar'.
public class Solution {
// Complete the aVeryBigSum function below.
static long aVeryBigSum(long[] ar) {
long size = ar[0];
long resultHere = 0;
int i = 0;
while (i < size){
resultHere += ar[1][i];
i++;
}
return resultHere;
}
I get this:
Solution.java:18: error: array required, but long found
resultHere += ar[1][i];
^
refer: https://www.hackerrank.com/challenges/a-very-big-sum/
for problem
Here resultHere += ar[1][i]; you are trying to access a two-dimensional array and the ar array is only one dimensional.
One Dimensional array:
long[] oneDimensional = new long[10];
Two dimensional array:
long[][] twoDimensional = new long[10][10];
public class Solution {
// Complete the aVeryBigSum function below.
static long aVeryBigSum(long[] ar) {
long size = ar[0];
long resultHere = 0;
int i = 1;
while (i < size){
resultHere += ar[i];
i++;
}
return resultHere;
}
Hey guys I am trying to get the number of people who have the same birthday but this solution isn't working.This program is showing 0.0% .Please help me ...!.
public double calculate(int size, int count) {
int matches = 0;//initializing an integer variable
boolean out = false;
List<Integer> days=new ArrayList<Integer>();// creating arraylist name days of type int
for (int j = 0; j <count; j++) {
for (int i = 0; i < size; i++) {// initializing for loop till less than size
Random rand = new Random(); // creating an object of random function
int Brday = rand.nextInt(364) + 0;//initializing the limit of randomc number chozen
days.add(Brday); //adding values to arraylist
}
for (int l = 0; l < size; l++) {
int temp = l;//assigning value of l to a variable
for (int k = l + 1; k < size; k++) {
if (days.get(k) == temp) {// check statement to check values are same
matches++;//incrementing variable
out = true;
mOut.print("Count does have same birthday" + matches);
break;
} else {
mOut.print("does not have same birthday");
}
}
if (out) {
out = false;
break;
}
}
}
double prob = (double) matches / count;
mOut.print("The probability for two students to share a birthday is " + prob*100 + ".");
return prob;//returning double value of the function
}
Actually, you get either 0 percent or 100 percent with your code. Try invoking it with calculate(100, 100) if you want to see.
There are two things that are wrong in this code. First, if you run the simulation more than once (count > 1) then you never clear the list of birthdays before the second iteration.
Your method should begin with:
public double calculate(int size, int count) {
int matches = 0;
boolean out = false;
List<Integer> days;
for (int j = 0; j <count; j++) {
days = new ArrayList<Integer>();
Secondly, you're not comparing two birthdays but you're comparing a birthday to the index in the list.
This line:
int temp = l;//assigning value of l to a variable
Should read:
int temp = days.get(l); // Remember the birthday at index l
With those changes you'll get a much better result.
this code doesn't function,
it said that lessthaAverage(int) in calculateArray cannot be applied to (), I'm a beginner so I still don't understand this coding yet, this is the question ask, Write an object oriented program that randomly generates an array of 1000 integers between 1 to 1000.
Calculate the occurrences of number more than 500 and find the average of the numbers.
Count the number which is less than the average and finally sort the numbers in descending order.
Display all your output. Please do HELP ME!!!,Thank You...
import java.util.*;
import java.io.*;
//import java.util.random;
public class CalculateArray
{
//declare attributes
private int arr[] = new int[1000];
int i;
//generates an array of 1000 integers between 1 to 1000
public void genArr()
{
Random ran = new Random();
for(i = 0; i < arr.length; i++)
{
arr[i] = ran.nextInt(1000) + 1;
}
}
//Calculate the occurences of number more than 500
public int occNumb()
{
int count;
for(i = 0; i < arr.length; i++)
{
if(arr[i] > 500)
{
count++;
}
}
return count;
}
//find the average of the numbers
public int average()
{
int sum, aver;
for(i = 0; i < arr.length; i++)
{
sum += arr[i];
}
aver = sum/1000;
return aver;
}
//Count the number which is less than the average
public int lessthanAverage(int aver)
{
int cnt;
cnt = 0;
for(i = 0; i < arr.length; i++)
{
if(arr[i] < aver)
{
cnt++;
}
}
return cnt;
}
//finally sort the numbers in descending order.
public void sort(int[] num)
{
System.out.println("Numbers in Descending Order:" );
for (int i=0; i <= num.length; i++)
for (int x=1; x <= num.length; x++)
if (num[x] > num[x+1])
{
int temp = num[x];
num[x] = num[x+1];
num[x+1] = temp;
}
}
//Display all your output
public void display()
{
int count, aver;
System.out.println(arr[i] + " ");
System.out.println("Found " + count + " values greater than 500");
System.out.println("The average of the numbers is " + aver);
System.out.println("Found " + count + " values that less than average number ");
}
public static void main(String[] args)
{
CalculateArray show = new CalculateArray();
show.genArr();
int c= show.occNumb();
show.average();
int d=show.lessthanAverage();
show.sort(arr);
show.display();
}
}
Your method lessthanAverage is expecting a int parameter. You should store the result of the average method call into a int variable and pass it to the call to lessthanAverage.
int avg = show.average();
int d=show.lessthanAverage(avg);
Your lessthaAverage() method expects an average to be passed in as a parameter, but you are not passing it in when you call it.
It seems that your method lessthanAverage needs an int as a parameter, but you are not passing it in main
public int lessthanAverage(int aver)
In main aver is not being passed:
int d=show.lessthanAverage(); // where is aver?
But if you wanted to know the average inside the method you could call your average method inside lessthanAverage:
if(arr[i] < this.average())
and not pass any parameter at all:
public int lessthanAverage()