How do I fix this array output? - java

I'm making a histogram program in which I have one array that generates a random number, another that makes them into an array, and a last one that attempts to use that array and tell how many characters are in each [] of the array. My problem is that I cannot find a way to count how many characters are in each array element and outprint it. I'm trying to use the .length function but it doesn't seem to be working. Is there another way that I could do this?
Here is my code. My problem is with my last method, before my main method.
package arrayhistogram;
/**
*
* #author Dominique
*/
public class ArrayHistogram {
public static int randomInt(int low, int high){
double x =Math.random ()* (high - low)+low;
int x1=(int)x;
return x1;
}
public static int[] randomIntArray(int n){
int[] a = new int[n];
for (int i=0; i<n; i++) {
a[i] = randomInt(-5, 15);
}
return a;
}
public static int[] arrayHist () {
int[] x=randomIntArray(30);
for (int i = 0; i < x.length; i++) {
System.out.println(x[i].length);
}
return x;
}
public static void main(String[] args) {
arrayHist();
}
}

Replace
System.out.println(x[i].length);
with
System.out.println(Integer.toString(x[i]).length());

There is no length property on an int. You can use this to get the number of digits in the int.
String.valueOf(x[i]).length()
This first transforms the int into a String and then returns the length of that String. E.g 123 => "123", whose length is 3.

Related

what is the error in my code of CSES problem static range sum query

I am trying to solve this problem https://cses.fi/problemset/task/1646. Why am I getting Runtime error an array of up to 200000 elements? Where am I wrong. I used a sparse Table to solve that problem.
static long st[][] = new long[100000][k+1]
what should be the size of 2d array st[][].
My Code:
class Mai{
static int n;
static int k=17;
static long st[][] = new long[100000][k+1];
public static void main(String[] args) throws IOException {
Reader sc = new Reader();
int n =sc.nextInt();
long q =sc.nextLong();
long a[] = new long[10000000];
for(int i=0;i<n;i++){
a[i]=sc.nextInt();
}
for(int i=0;i<n;i++){
st[i][0]=a[i];
}
for(int j=1;j<k;j++){
for(int i=0;i+(1<<j)<=n;i++){
st[i][j] = st[i][j-1] + st[i + (1 << (j - 1))][j - 1];
}
}
while(q-->0){
int l= sc.nextInt();
int r =sc.nextInt();
l--;
r--;
query(l,r);
}
}
public static void query(int l,int r){
long sum=0;
for(int j=k;j>=0;j--){
if((1<<j)<=(r-l+1)){
sum+=st[l][j];
l+=1<<j;
}
}
System.out.println(sum);
}
}
And the error I'm getting is shown in here
look look at here, you may get some help..
We will use a 2-dimensional array for storing the answers to the precomputed queries. st[i][j] will store the answer for the range [i,i+2j−1] of length 2j. The size of the 2-dimensional array will be MAXN×(K+1), where MAXN is the biggest possible array length. K has to satisfy K≥⌊log2MAXN⌋, because 2⌊log2MAXN⌋ is the biggest power of two range, that we have to support. For arrays with reasonable length (≤107 elements), K=25 is a good value.

How do I rerun a static integer array?

here's the array I want to rerun:
public static int[] rollDice(int dice[]) {
// generate 5 random numbers / update dice array
for (int i = 0; i < dice.length; i++) {
dice[i] = (int)(Math.random() * 6 + 1);
}
return dice;
}
If I want to reset this array and find new random numbers how would I do that? I tried rollDice() only to get an error.
There is no point in returning the array, since you already have a reference to the array when you call the method rollDice().
Arrays are sent by reference and not by value, which means you are not working with a copy like you do with ints, instead you are modifing the original array.
Change the return type to void and remove the return and your code should work as intended.
You can get every time a new dynamic length array with random numbers, and you can access by call rollDice(integer value).
public static int[] rollDice(int length) {
final int dice[] = new int [length];
// generate array with random values
for (int i = 0; i < length; i++) {
dice[i] = (int)(Math.random() * length + 1);
}
return dice;
}
You would have to have a class member like this:
public static final int[] dice = new int[5];
Then to roll/reroll the dice use your method, else just access dice.
public static void rollDice() {
// generate 5 random numbers / update dice array
for (int i = 0; i < dice.length; i++) {
dice[i] = (int)(Math.random() * 6 + 1);
}
}
Interesting fact: Java has no static function variables as C and C++ does. In those languages it could look like this:
(I wrote it like a java Function for you Java guys)
public static int[5] rollDice(boolean reroll) {
static final int[] dice = new int[5];
if (reroll) for (int i = 0; i < dice.length; i++) {
dice[i] = (int)(Math.random() * 6 + 1);
}
return dice;
}
As you can see, static variables can be embedded into those functions. If you ask me, it's a huge minus, Java doesn't support this as I use it all the time to hide those from the class namespace.

Finding the occurrence of values within an array

My question is how do I find the frequency of the numbers "8" and "88" in this array, using a method. It seems as what I put in the assessor method does not appear to work. For example, if "8" occurs three times in the array the output would be "3" and the same for "88".
If I am wrong please point me to the right direction. Any help with my question is greatly appreciate.
import java.util.Random;
public class ArrayPractice {
private int[] arr;
private final int MAX_ARRAY_SIZE = 300;
private final int MAX_VALUE = 100;
public ArrayPractice() {
// initialize array
arr = new int[MAX_ARRAY_SIZE];
// randomly fill array with numbers
Random rand = new Random(1234567890);
for (int i = 0; i < MAX_ARRAY_SIZE; ++i) {
arr[i] = rand.nextInt(MAX_VALUE) + 1;
}
}
public void printArray() {
for (int i = 0; i < MAX_ARRAY_SIZE; ++i)
System.out.println(arr[i]);
}
public int countFrequency(int value) {
for (int i: MAX_VALUE) {
if (i == 8)
i++;
}
public static void main(String[] args) {
ArrayPractice ap = new ArrayPractice();
System.out.println("The contents of my array are: ");
ap.printArray();
System.out.println("");
System.out.println("The frequency of 8 is: " + ap.countFrequency(8));
System.out.println("The frequency of 88 is: " + ap.countFrequency(88));
}
}
}
You need to iterate over arr and increment a variable when an element matches value.
public int countFrequency(int value) {
int count = 0;
for (int num : arr) {
if (num == value) {
count++;
}
}
return count;
}
You have a hard-coded seed, so your random values won't be random on different runs. You are also hard-coding your frequency count against 8 (instead of value). But honestly, I suggest you revisit this code with lambdas (as of Java 8), they make it possible to write the array generation, the print and the count routines in much less code. Like,
public class ArrayPractice {
private int[] arr;
private final int MAX_ARRAY_SIZE = 300;
private final int MAX_VALUE = 100;
public ArrayPractice() {
// randomly fill array with numbers
Random rand = new Random();
arr = IntStream.generate(() -> rand.nextInt(MAX_VALUE) + 1)
.limit(MAX_ARRAY_SIZE).toArray();
}
public void printArray() {
IntStream.of(arr).forEachOrdered(System.out::println);
}
public int countFrequency(int value) {
return (int) IntStream.of(arr).filter(i -> i == value).count();
}
}
You need to iterate over the array and increment a counter variable when an element matches i
what you are doing is increment i instead of a counter:
if (i == 8)
i++;
} // if i is 8 then i becomes 9
A working example:
public int countFrequency(int i) {
int count = 0;
for (int num : arr) {
if (num == i) {
count++;
}
}
return count;
}
Solution:
public int countFrequency(int value) {
int counter = 0; // here you will store counter of occurences of value passed as argument
for (int i : arr) { // for each int from arr (here was one of your errors)
if (i == value) // check if currently iterated int is equal to value passed as argument
counter++; // if it is equal, increment the counter value
}
return counter; // return the result value stored in counter
}
Explanation:
Main problem in your code was countFrequency() method, there are few bugs that you need to change if you want to make it work correctly:
You passed value as argument and you didn't even use it in the body of method.
for (int i : MAX_VALUE ) - you meant to iterate over elements of arr array, (You can read it then as: For each int from arr array do the following: {...}.
if (i == 8) i++ - here you said something like this: Check if the current element from array (assuming that you meant MAX_VALUE is an array) is equal to 8, and if it is - increment this value by 1 (so if it were 8, now it's 9). Your intention here was to increment counter that counts occurences of 8.
You might want to consider making these improvements to countFrequency() method, to make it work properly.

What is the best way to check if ALL values in a range exist in an array? (java)

I have the task of determining whether each value from 1, 2, 3... n is in an unordered int array. I'm not sure if this is the most efficient way to go about this, but I created an int[] called range that just has all the numbers from 1-n in order at range[i] (range[0]=1, range[1]=2, ect). Then I tried to use the containsAll method to check if my array of given numbers contains all of the numbers in the range array. However, when I test this it returns false. What's wrong with my code, and what would be a more efficient way to solve this problem?
public static boolean hasRange(int [] givenNums, int[] range) {
boolean result = true;
int n = range.length;
for (int i = 1; i <= n; i++) {
if (Arrays.asList(givenNums).containsAll(Arrays.asList(range)) == false) {
result = false;
}
}
return result;
}
(I'm pretty sure I'm supposed to do this manually rather than using the containsAll method, so if anyone knows how to solve it that way it would be especially helpful!)
Here's where this method is implicated for anyone who is curious:
public static void checkMatrix(int[][] intMatrix) {
File numberFile = new File("valid3x3") ;
intMatrix= readMatrix(numberFile);
int nSquared = sideLength * sideLength;
int[] values = new int[nSquared];
int[] range = new int[nSquared];
int valCount = 0;
for (int i = 0; i<sideLength; i++) {
for (int j=0; j<sideLength; j++) {
values[valCount] = intMatrix[i][j];
valCount++;
}
}
for (int i=0; i<range.length; i++) {
range[i] = i+1;
}
Boolean valuesThere = hasRange(values, range);
valuesThere is false when printed.
First style:
if (condition == false) // Works, but at the end you have if (true == false) or such
if (!condition) // Better: not condition
// Do proper usage, if you have a parameter, do not read it in the method.
File numberFile = new File("valid3x3") ;
intMatrix = readMatrix(numberFile);
checkMatrix(intMatrix);
public static void checkMatrix(int[][] intMatrix) {
int nSquared = sideLength * sideLength;
int[] values = new int[nSquared];
Then the problem. It is laudable to see that a List or even better a Set approach is the exact abstraction level: going into detail not sensible. Here however just that is wanted.
To know whether every element in a range [1, ..., n] is present.
You could walk through the given numbers,
and for every number look whether it new in the range, mark it as no longer new,
and if n new numbers are reached: return true.
int newRangeNumbers = 0;
boolean[] foundRangeNumbers = new boolean[n]; // Automatically false
Think of better names.
You say you have a one dimensional array right?
Good. Then I think you are thinking to complicated.
I try to explain you another way to check if all numbers in an array are in number order.
For instance you have the array with following values:
int[] array = {9,4,6,7,8,1,2,3,5,8};
First of all you can order the Array simpel with
Arrays.sort(array);
After you've done this you can loop through the array and compare with the index like (in a method):
for(int i = array[0];i < array.length; i++){
if(array[i] != i) return false;
One way to solve this is to first sort the unsorted int array like you said then run a binary search to look for all values from 1...n. Sorry I'm not familiar with Java so I wrote in pseudocode. Instead of a linear search which takes O(N), binary search runs in O(logN) so is much quicker. But precondition is the array you are searching through must be sorted.
//pseudocode
int range[N] = {1...n};
cnt = 0;
while(i<-inputStream)
int unsortedArray[cnt]=i
cnt++;
sort(unsortedArray);
for(i from 0 to N-1)
{
bool res = binarySearch(unsortedArray, range[i]);
if(!res)
return false;
}
return true;
What I comprehended from your description is that the array is not necessarily sorted (in order). So, we can try using linear search method.
public static void main(String[] args){
boolean result = true;
int[] range <- Contains all the numbers
int[] givenNums <- Contains the numbers to check
for(int i=0; i<givenNums.length; i++){
if(!has(range, givenNums[i])){
result = false;
break;
}
}
System.out.println(result==false?"All elements do not exist":"All elements exist");
}
private static boolean has(int[] range, int n){
//we do linear search here
for(int i:range){
if(i == n)
return true;
}
return false;
}
This code displays whether all the elements in array givenNums exist in the array range.
Arrays.asList(givenNums).
This does not do what you think. It returns a List<int[]> with a single element, it does not box the values in givenNums to Integer and return a List<Integer>. This explains why your approach does not work.
Using Java 8 streams, assuming you don't want to permanently sort givens. Eliminate the copyOf() if you don't care:
int[] sorted = Arrays.copyOf(givens,givens.length);
Arrays.sort(sorted);
boolean result = Arrays.stream(range).allMatch(t -> Arrays.binarySearch(sorted, t) >= 0);
public static boolean hasRange(int [] givenNums, int[] range) {
Set result = new HashSet();
for (int givenNum : givenNums) {
result.add(givenNum);
}
for (int num : range) {
result.add(num);
}
return result.size() == givenNums.length;
}
The problem with your code is that the function hasRange takes two primitive int array and when you pass primitive int array to Arrays.asList it will return a List containing a single element of type int[]. In this containsAll will not check actual elements rather it will compare primitive array object references.
Solution is either you create an Integer[] and then use Arrays.asList or if that's not possible then convert the int[] to Integer[].
public static boolean hasRange(Integer[] givenNums, Integer[] range) {
return Arrays.asList(givenNums).containsAll(Arrays.asList(range));
}
Check here for sample code and output.
If you are using ApacheCommonsLang library you can directly convert int[] to Integer[].
Integer[] newRangeArray = ArrayUtils.toObject(range);
A mathematical approach: if you know the max value (or search the max value) check the sum. Because the sum for the numbers 1,2,3,...,n is always equal to n*(n+1)/2. So if the sum is equal to that expression all values are in your array and if not some values are missing. Example
public class NewClass12 {
static int [] arr = {1,5,2,3,4,7,9,8};
public static void main(String [] args){
System.out.println(containsAllValues(arr, highestValue(arr)));
}
public static boolean containsAllValues(int[] arr, int n){
int sum = 0;
for(int k = 0; k<arr.length;k++){
sum +=arr[k];
}
return (sum == n*(n+1)/2);
}
public static int highestValue(int[]arr){
int highest = arr[0];
for(int i = 0; i < arr.length; i++) {
if(highest<arr[i]) highest = arr[i];
}
return highest;
}
}
according to this your method could look like this
public static boolen hasRange (int [] arr){
int highest = arr[0];
int sum = 0;
for(int i = 0; i < arr.length; i++) {
if(highest<arr[i]) highest = arr[i];
}
for(int k = 0; k<arr.length;k++){
sum +=arr[k];
}
return (sum == highest *(highest +1)/2);
}

Proper way of writing an int array and returning the number of elements?

I have a problem. I am trying to write a value-returning method that returns the number of elements in an integer array. I have the array written and have the return statement half right. I am lost at this point. how to I get the number of elements in the array, which is 9, into an int form and into the return statement?
Thank you
public class ChapterEightCode
{
public static void main(String[] args)
{
int eTotals = myArray();
System.out.println(eTotals);
}
static int myArray()
{
int[] intArray = new int[] {1,2,3,4,5,6,7,8,9};
for (int i=0; i<intArray.length; i++)
{
System.out.println(intArray[i]);
}
int eTotals = 1000;
return eTotals;
}
}
Not sure why you are looping if you're just after the array length, try this:
return intArray.length;
Use the length field of the array:
return intArray.length;
Observe this method carefully:
You're first creating an integer array, then looping through each element from 0 to length of intArray, printing the elements one by one. Then you declare an integer eTotals, set it to 1000 and then return eTotals which means, you're returning 1000 all the time.
static int myArray()
{
int[] intArray = new int[] {1,2,3,4,5,6,7,8,9};
for (int i=0; i<intArray.length; i++)
{
System.out.println(intArray[i]);
}
int eTotals = 1000;
return eTotals; // instead `return intArray.length;`
}
Why not just return intArray.length;?
if u write a "int eTotals = 1000; return eTotals;" in the last of the function myArray(),I will fell that the code before has no meaning。
Maybe u can try replace the statement "int eTotals=1000;" as "int eTotals = intArray.length;"

Categories

Resources