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;
}
Related
I figure I have the general idea down for how to solve the algorithm but the implementation seems to elude me. What I have thus far is this:
public class GreedySalesman {
public static int[] greedySalesmanSolution(int[][] distances) {
List cityList = new ArrayList();
for(int[] array: distances) {
cityList.add(Arrays.asList(array));
}
List<Integer> initialResult = new ArrayList();
initialResult.add(0);
List<Integer> finalResult = findMinDistance(cityList, cityList, initialResult, 0);
/*int finalResultArray = new int[finalResult.size()+1];
int i = 0;
while (!(finalResult.isEmpty)) {
finalResultArray[i] = finalResult.poll();
i++;
}
return finalResultArray;
*/
return null;
}
public static List<Integer> findMinDistance(List<List<Integer>> initialCityInput, List<List<Integer>> cityInput, List<Integer> distanceResult, int index) {
if(cityInput.isEmpty()) {
distanceResult.add(0);
return distanceResult;
}
int min = Collections.min(initialCityInput.get(index));
List<Integer> city = initialCityInput.get(index);
index = city.indexOf(min);
distanceResult.add(index);
cityInput.remove(city);
return findMinDistance(initialCityInput,cityInput,distanceResult,index);
}
}
That is, the algorithm will take an two dimensional array of ints as an input, then make a List cityList referring to distances, then pass it into findMinDistance. The commented out part is where the result from findMinDistance will be converted into an array of ints and returned as finalResultArray but that part is not important yet.
findMinDistance will take in a two dimensional list of Integers twice, a List of Integers that will become the result and an int representing an index.
The function will return the distanceResult when cityInput has been emptied. Otherwise it will start with the first city based on the index, get the minimum distance from that List and its index and add the index to the distanceResult.
Once that has been done, the city will be removed from the cityInput and the program will go into recursion until cityInput has been emptied.
The issue I am getting currently is
I cannot be cast to java.lang.Integer
at
int min = Collections.min(initialCityInput.get(index));
And in main upon trying to run the program with some test data.
Any help will be appreciated.
======
Edit:
I made some changes to my code
public class GreedyTSP {
public int[] greedySalesmanSolution(int[][] distances) {
List<List<Integer>> cityList = new ArrayList();
List<List<Integer>> initialCityList = new ArrayList();
int iLength = distances.length;
for (int i = 0; i < iLength; ++i) {
int jLength = distances[0].length;
cityList.add(new ArrayList(jLength));
initialCityList.add(new ArrayList(jLength));
for (int j = 0; j < jLength; ++j) {
cityList.get(i).add(distances[i][j]);
initialCityList.get(i).add(distances[i][j]);
}
}
List<Integer> initialResult = new ArrayList();
initialResult.add(0);
List<Integer> finalResult = findMinDistance(initialCityList, cityList, initialResult, 0);
int[] finalResultArray = new int[finalResult.size()];
Iterator<Integer> iterator = finalResult.iterator();
for (int i = 0; i < finalResultArray.length; i++){
finalResultArray[i] = iterator.next().intValue();
}
return finalResultArray;
}
public List<Integer> findMinDistance(List<List<Integer>> initialCityInput, List<List<Integer>> cityInput, List<Integer> distanceResult, int initialIndex) {
if(cityInput.isEmpty()) {
distanceResult.add(0);
return distanceResult;
}
List<Integer> city = initialCityInput.get(initialIndex);
Integer min = findMin(city, distanceResult, initialIndex);
int resultIndex = city.indexOf(min);
distanceResult.add(resultIndex);
cityInput.remove(city);
return findMinDistance(initialCityInput,cityInput,distanceResult,resultIndex);
}
public Integer findMin(List<Integer> city, List<Integer> distanceResult, int inputIndex) {
Integer min = Integer.MAX_VALUE;
for(int i = 0; i < city.size();i++) {
if (city.get(i) > inputIndex && city.get(i) < min) min = city.get(i);
}
int resultIndex = city.indexOf(min);
if(distanceResult.contains(resultIndex)) {
return findMin(city, distanceResult, inputIndex);
}
return min;
}
}
Im not having any cast errors at the moment but it seems that the parts of my program dealing with recursion are causing StackOverflowError-s. I've been messing with this thing for literally 16 hours now and I'm all out of ideas as to why. Any ideas?
The problem with your casting is the following
List<List<Integer>> initialCityInput is a List containing Lists with integers.
Therefore initalCityInput.get(index) returns a List not an Int, which cannot be cast to int.
Well, I looked around a bit and I was basically overcomplicating the task through using multidimensional arraylists. I changed the code quite a bit:
public class GreedyTSP {
public static int[] greedySolution(int[][] adjacencyMatrix) {
List<Integer> visitedCities = new ArrayList<>();
int min = Integer.MAX_VALUE;
int startLocation = 0;
int tempStartLocation = 0;
int[] resultArray = new int[adjacencyMatrix.length+1];
visitedCities.add(0);
while(visitedCities.size() < adjacencyMatrix.length ){
for(int i = 0; i < adjacencyMatrix.length; i++){
if(!visitedCities.contains(i) && adjacencyMatrix[startLocation][i] < min){
min = adjacencyMatrix[startLocation][i];
tempStartLocation = i;
}
}
startLocation = tempStartLocation;
visitedCities.add(tempStartLocation);
min = Integer.MAX_VALUE;
}
visitedCities.add(0);
for(int i = 0; i < resultArray.length; i++){
int temp = visitedCities.get(i);
resultArray[i] = temp;
}
return resultArray;
}
}
This will solve the task using a greedy algorithm
I'm building a class that takes an array of numbers and has methods to output their min, max and average values as a string representation of the numbers. Here's my constructor for the class:
public RandomArray(int sizeOfArray)/*Constructor: gets array size and populates array with
random numbers*/
{
Random generator = new Random();
size = sizeOfArray;
for (int i = 0;i < size;i++)
{
numbers[i] = generator.nextInt(size + 1);
}
}
I'm getting the array out of bounds exception message when I test this class with a driver program and this constructor is the one causing it. I'm not able to understand how I'm going beyond the size of the array here. Please help! Thanks.
Edit - So just to clear up any confusion I'm posting the entire class below for reference:
public class RandomArray
{
/*A class that contains an array of random numbers and methods that output
the numbers' minimum, maximum and average values. Also includes a method
that outputs a string representation of the numbers.*/
int size, min, max;
String array;
int[] numbers = new int[size];
public RandomArray(int sizeOfArray)/*Constructor: gets array size and populates array with
random numbers*/
{
Random generator = new Random();
size = sizeOfArray;
for (int i = 0;i < size;i++)
{
numbers[i] = generator.nextInt(size + 1);
}
}
public int min_value()
{
for (int i = 0;i < size - 1;i++)
{
min = numbers[i];
for (int k = 1;k < size; k++)
{
if (numbers[k] < min)
{
min = numbers[k];
}
else
{
min = numbers[i];
}
}
}
return min;
}
public int max_value()
{
for (int i = 0;i < size - 1;i++)
{
max = numbers[i];
for (int k = 1;k < size; k++)
{
if (numbers[k] > max)
{
max = numbers[k];
}
else
{
max = numbers[i];
}
}
}
return max;
}
public double average()
{
double avg;
int sum = 0;
for (int i = 0;i < size;i++)
{
sum = sum + numbers[i];
}
avg = sum/size;
return avg;
}
public String toStringArray()//Outputs a string representation of all the numbers in the array
{
for (int i = 0; i < size;i++)
{
array = Integer.toString(numbers[i]) + " ";
}
return array;
}
}
You are initializing the array before you initialize the size variable. The size variable has a default value which is passed into the array constructor and sets the array to that size. to fix the problem just move the initialization of the array into the constructor after the size variable is set.
public class RandomArray
{
/*A class that contains an array of random numbers and methods that output
the numbers' minimum, maximum and average values. Also includes a method
that outputs a string representation of the numbers.*/
int size, min, max;
String array;
int[] numbers;
public RandomArray(int sizeOfArray) {
Random generator = new Random();
size = sizeOfArray;
numbers = new int[size];
for (int i = 0;i < size;i++)
{
numbers[i] = generator.nextInt(size + 1);
}
}
Also I've noticed a bug with the string output method. The array would be overwritten on each iteration. To solve this you must add the array to itself.
public String toStringArray()//Outputs a string representation of all the numbers in the array
{
for (int i = 0; i < size;i++)
{
array = array + Integer.toString(numbers[i]) + " ";
}
return array;
}
Your method is passed the size of the array, but the array definition is not present in your code.
If you need to create the array in the RandomArray method, do something like :
public int[] RandomArray(int sizeOfArray)/*Constructor: gets array size, create and populates array with random numbers*/
{
int[] randomArray = new int[sizeOfArray];
for (int i = 0;i < randomArray.length();i++)
{
numbers[i] = generator.nextInt(size + 1);
}
return randomArray;
}
As you did not provide the entire class code it is hard to see whats going on. However I think you did not initialize the array correctly. If you have a private variable for an array, you should still 'make space' for it, as follows.
private int[] myIntArray; // As class member
myIntArray = new int[3]; // To allocate memory for the array
See the following link, for more info regarding arrays.
https://docs.oracle.com/javase/tutorial/java/nutsandbolts/arrays.html
I want to write a java program which will calculate the first 20 factorial and store them in an array. Then go through the array and sum all of the items and print the result on the screen.
Here is my code but I think I did something wrong:
public class ArrayQuestion4 {
public static void main(String[] args) {
long array[]= new long[20];
long temp=1;
for ( int i=1; i<20; i++){
temp = i*(i+1);
temp = temp*(temp+1);
array[i]=temp;
System.out.println(array[i]);
}
for ( int i=1; i<20; i++){
temp = array[i];
temp = array[i]+(array[i+1]);
temp = temp+(temp+1);
System.out.println(temp);
}
}
}
The answer that comes out is not correct by the way.
I figure it out the correct code is this:
public class ArrayQuestion4 {
public static void main(String[] args) {
long array[]= new long[20];
array[0]=1;
long temp=0;
for ( int i=1; i<20; i++){
array[i]=array[i-1]*(i+1);
System.out.println(array[i-1]+"*"+(i+1)+" = "+array[i]);
}
for ( int i=1; i<20; i++){
temp = temp + array[i-1] + array[i];
}
System.out.println(" ");
System.out.println("Sum = "+temp);
}
}
The way you define factorial of n is
fact(n) = n * fact(n-1)
In the solution, factorial[n] represents factorial(n).
and temp is the current factorial being calculated.
public static void main(String[] args) {
long factorial[] = new long[20];
//Because Fact(1) = 1 * Fact(0), and fact(0) = 1.
factorial[0] = 1;
for (int n = 1; n < 20; n++) {
// Loop needs to be <20 because i have defined the array size = 20.
// <= would get an array out of bound exception. You can change the limits as you want.
//calculating the factorial based on formula:
// Factorial(N) = n * Facorial(N-1);
long factorialOfN = n*factorial[n-1];
//storing back the value in the array for future use.
factorial[n] = factorialOfN;
//Printing it.
System.out.println(factorialOfN);
}
}
As an illustration of where the code is probably not doing what you want it to be doing, look at what you get for (2)!
temp = i*(i+1); //temp = 1*(1+1); which is 2
temp = temp*(temp+1); //temp = 2*(2+1); which is 6
array[i] = temp; //array[1] = 6; - also note we skip ever assigning array[0]
You get 6 as an answer, which is incorrect.
Long could not hold sum of all 20! results. There is a limit for 'long' in Java and it is
public static final long MAX_VALUE = 0x7fffffffffffffffL;
which is 9223372036854775807
Use 'BigInteger' to get correct answer. And also refer 'How (not) to write Factorial in Java'
So I created an array with random numbers, i printed and counted the repeated numbers, now I just have to create a new array with the same numbers from the first array but without any repetitions. Can't use ArrayList by the way.
What I have is.
public static void main(String[] args) {
Random generator = new Random();
int aR[]= new int[20];
for(int i=0;i<aR.length;i++){
int number=generator.nextInt(51);
aR[i]=number;
System.out.print(aR[i]+" ");
}
System.out.println();
System.out.println();
int countRep=0;
for(int i=0;i<aR.length;i++){
for(int j=i+1;j<aR.length-1;j++){
if(aR[i]==aR[j]){
countRep++;
System.out.println(aR[i]+" "+aR[j]);
break;
}
}
}
System.out.println();
System.out.println("Repeated numbers: "+countRep);
int newaR[]= new int[aR.length - countRep];
}
Can someone help?
EDIT: Can't really use HashSet either. Also the new array needs to have the correct size.
Using Java 8 and streams you can do the following:
int[] array = new int[1024];
//fill array
int[] arrayWithoutDuplicates = Arrays.stream(array)
.distinct()
.toArray();
This will:
Turn your int[] into an IntStream.
Filter out all duplicates, so retaining distinct elements.
Save it in a new array of type int[].
Try:
Set<Integer> insertedNumbers = new HashSet<>(newaR.length);
int index = 0;
for(int i = 0 ; i < aR.length ; ++i) {
if(!insertedNumbers.contains(aR[i])) {
newaR[index++] = aR[i];
}
insertedNumbers.add(aR[i]);
}
One possible approach is to walk through the array, and for each value, compute the index at which it again occurs in the array (which is -1 if the number does not occur again). The number of values which do not occur again is the number of unique values. Then collect all values from the array for which the corresponding index is -1.
import java.util.Arrays;
import java.util.Random;
public class UniqueIntTest
{
public static void main(String[] args)
{
int array[] = createRandomArray(20, 0, 51);
System.out.println("Array " + Arrays.toString(array));
int result[] = computeUnique(array);
System.out.println("Result " + Arrays.toString(result));
}
private static int[] createRandomArray(int size, int min, int max)
{
Random random = new Random(1);
int array[] = new int[size];
for (int i = 0; i < size; i++)
{
array[i] = min + random.nextInt(max - min);
}
return array;
}
private static int[] computeUnique(int array[])
{
int indices[] = new int[array.length];
int unique = computeIndices(array, indices);
int result[] = new int[unique];
int index = 0;
for (int i = 0; i < array.length; i++)
{
if (indices[i] == -1)
{
result[index] = array[i];
index++;
}
}
return result;
}
private static int computeIndices(int array[], int indices[])
{
int unique = 0;
for (int i = 0; i < array.length; i++)
{
int value = array[i];
int index = indexOf(array, value, i + 1);
if (index == -1)
{
unique++;
}
indices[i] = index;
}
return unique;
}
private static int indexOf(int array[], int value, int offset)
{
for (int i = offset; i < array.length; i++)
{
if (array[i] == value)
{
return i;
}
}
return -1;
}
}
This sounds like a homework question, and if it is, the technique that you should pick up on is to sort the array first.
Once the array is sorted, duplicate entries will be adjacent to each other, so they are trivial to find:
int[] numbers = //obtain this however you normally would
java.util.Arrays.sort(numbers);
//find out how big the array is
int sizeWithoutDuplicates = 1; //there will be at least one entry
int lastValue = numbers[0];
//a number in the array is unique (or a first duplicate)
//if it's not equal to the number before it
for(int i = 1; i < numbers.length; i++) {
if (numbers[i] != lastValue) {
lastValue = i;
sizeWithoutDuplicates++;
}
}
//now we know how many results we have, and we can allocate the result array
int[] result = new int[sizeWithoutDuplicates];
//fill the result array
int positionInResult = 1; //there will be at least one entry
result[0] = numbers[0];
lastValue = numbers[0];
for(int i = 1; i < numbers.length; i++) {
if (numbers[i] != lastValue) {
lastValue = i;
result[positionInResult] = i;
positionInResult++;
}
}
//result contains the unique numbers
Not being able to use a list means that we have to figure out how big the array is going to be in a separate pass — if we could use an ArrayList to collect the results we would have only needed a single loop through the array of numbers.
This approach is faster (O(n log n) vs O (n^2)) than a doubly-nested loop through the array to find duplicates. Using a HashSet would be faster still, at O(n).
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.