i new to Java, i want to know if its possible to access a array of size 0?I in a Java course and there a problem to solve where we need to calculate the sum of all element in a array,and if this sum is bigger than 100, we return true. We also need to calculate only positive number, no negative,and finally the code must work even if the array is empty. That my code here:
public static boolean biggerOrLower(){
int data[] =new int[0];
//data = new int[] {0,0,0,0,44,44,66,66,33,444,555,453,};
int iterator = 0;
boolean exced = false;
int sum = 0;
while(iterator < data.length)
{
if(iterator > 0) {
sum = sum + data[iterator];
if (sum > 100) {
exced = true;
break;
}
}
else
{
exced = false;
}
System.out.println(sum);
iterator++;
}
System.out.println(exced);
return exced;
}
}
The problem is, since iterator is = 0 , and the length of data is also 0, it never enter the while loop, but it need too, and if i change the code to while (iterator <= data.length) i got a Exception Index 0 out of bounds for length 0.
Can somebody tell why that happen and how i ca fix that?
Thank
im also a bit new to java but i think this will work
public static boolean biggerOrLower(){
int data[] =new int[0];
//data = new int[] {0,0,0,0,44,44,66,66,33,444,555,453,};
boolean exced = false;
int sum = 0;
for(int i: data){
if(i > 0){ sum += i}
}
exced = sum > 100;
System.out.println(sum);
System.out.println(exced);
return exced;
}
i don't think you need to enter the loop and i believe a for loop is much better at solving this problem
Why do you have to enter the while loop. I don't see it is necessary. You cannot access something that is empty. If you want to execute some code if the array is of size 0 you can do that with an if clause.
Related
I am not sure if it's rly possible to check but I have an issue rn where I have an array
let's say: int[] unmarkedSum = new int[100];
Now I put something in this array when a certain condition is true so not in every single iteration. But I know for a fact that at some point the whole array will be filled with any positive values that are not 0 because of how my algorithm works.
My question here is: Is there a way of checking WHEN it's fully filled?
Like I started like this:
for(int i = 0; i < unmarkedSum.length; i++) {
if(unmarkedSum[i] == 0 {
break;
}
else {
// idk tbh
}
}
In Java by default an array of ints is filled with zeros. You can use this to check if the array is fully filled. For example you can create a method which checks for 0 and returns true if there are no 0:
public static bool isArrayFilled(int[] array) {
for(int i = array.length; i >= 0; i--){
if(array[i] == 0) {
return false;
}
}
return true;
}
If array is big enough and filled out of order, you can use advanced algorithms to find at least one 0 value in the array.
I would simply maintain a variable size that keep tracks of how many values have been written to the array.
Example:
int size = 0;
int[] array = new int[100];
Random r = new Random();
while(size < array.length){
int index = r.nextInt(100);
int val = r.nextInt(1000)+500;
if (array[index] == 0){
array[index] = val;
size++;
}
}
System.out.println(Arrays.toString(array));
Per my previous comment, you can share this array with another thread so that one thread can fill the values and another can check the array at the same time. When the second thread finds that there are no default values (or 0s) then it can notify the first thread (or the main thread). Here is how you can do that
import java.util.Arrays;
import java.util.Random;
public class CheckArray {
public static void main(String[] args) throws InterruptedException {
var arr = new int[50];
Thread arrayChecker = new Thread(() -> {
var isZeroPresent = false;
while (true) {
for (int index = 0; index < arr.length; index++) {
isZeroPresent = false;
if (arr[index] == 0) {
isZeroPresent = true;
break;
}
}
if (isZeroPresent == false) {
// if the for loop completed then control will come here
System.out.println("Array has been filled");
System.out.println(Arrays.toString(arr));
System.exit(0);
}
}
});
arrayChecker.start();
// fill random values in the array
// while another thread has been started
Random random = new Random();
while(true) {
Thread.sleep(500);
int index = random.nextInt(arr.length);
arr[index] = random.nextInt(100);
System.out.println(Arrays.toString(arr));
}
}
}
I am struggling here to see if my linear probing technique is correct and if it is efficient at all. Is there any way for me to make it more efficient?
static void enterValues(int values[], int hashTable[])
{
for(int i = 0; i < values.length; i++){
int k = hashFunction(values[i]);
if(hashTable[k]== 0)
hashTable[k] = values[i];
else{
boolean b = false;
int counter = k%hashTable.length+1;
if(counter >= hashTable.length)
counter = 0;
while (!b) {
if (hashTable[counter] == 0) {
hashTable[counter] = values[i];
b = true;
} else {
counter = counter % hashTable.length+1;
}
}
}
}
}
static int hashFunction(int value)
{
return value % 10;
}
int values[] = {4371,1323,6173,4199,4344,9679,1989};
the output for the size 10 hashset is
9679,
4371,
1989,
1323,
6173,
4344,
0,
0,
0,
4199
Thank you for taking a look
Why your hash function just returns value % 10? It's better to return value % hashTable.length. I'd suggest you to use Integer.hashCode and then do a modulus with hashTable.length
int counter = k%hashTable.length+1;
if(counter >= hashTable.length)
counter = 0;
These two statements can be replaced by: int counter = k % hashTable.length
To make it more efficient you can have additional book-keeping where you store the unfilled indices in hash table, and while filling you query this unfilled array (or a better data-structure - which can be sorted-tree to make searching, insertion and deletion faster) when you have clashes.
It is incorrect. Consider what happens if value[i] is zero:
if (hashTable[k] == 0) {
hashTable[k] = values[i];
} else { .... }
Since you are using zero in the hashtable to mean that the entry is not used, and you are also assigning values directly into the table, your code cannot distinguish a zero value from an empty entry.
I am using this method with the intentions of finding the most common element in an array. It works most of the time but for some reason it doesn't always work. I would also like it to be able to store if there are 2 numbers tied for most common but I am unsure how to do so.
Here is the code for the method: (The variable size is the size of the array)
public static int mostCommon(int size) {
int mostCommon = 0, mostCommonCount = 0, currentCount = 0;
for (int i = 1; i < size; i++) {
if (array[i - 1] == array[i]) {
currentCount++;
if (currentCount > mostCommonCount) {
mostCommonCount = currentCount;
mostCommon = array[i];
}
}
else
currentCount = 0;
}
return mostCommon;
}
This code is in the main and prints out the most common element:
if (mostCommon(size) == 0)
System.out.println("\nAll Elements In Your Array Occur Equally");
else
System.out.println("\nThe Most Common Element In Your Array Is: " + mostCommon(size));
I would really appreciate the help. Thanks!
Guessing this is irrelevant now but thought I would answer anyway.
I don't fully understand why you would pass the size of the array in but not the array itself, anyway, I have a solution, slightly modified from your method signature but if it is still needed then it can be modified to suit your exact situation.
public static Set<Integer> mostCommon()
{
int[] array = new int[] {1,2,3,4,5,5,4,3,4};
Map<Integer, Integer> counts = new HashMap<Integer,Integer>();
Set<Integer> highestCount = new TreeSet<Integer>();
//loop through the array to count common values
for(int numInArray : array)
{
//if number in array already been seen
if(counts.containsKey(numInArray))
{
counts.put(numInArray, counts.get(numInArray)+1);
}
//else set it at one
else
{
counts.put(numInArray, 1);
}
}
//loop through map to count highest occurences
int maxValue = 0;
int maxKey = 0;
for(Integer mapKey : counts.keySet())
{
int value = counts.get(mapKey);
//if value is greater than maxValue then set maxVale=value, also clear highestCount as they are lower now
if(value > maxValue)
{
highestCount.clear();
maxValue = value;
maxKey = mapKey;
}
//if value is the same as maxValue then store it in list, this will allow us to get two of the same max occurences
else if(value == maxValue)
{
highestCount.add(mapKey);
}
}
highestCount.add(maxKey);
System.out.println("counts " + counts);
System.out.println("final answer " + highestCount);
return highestCount;
}
I have tested various values in the array and it seems to work for all I tried.
This is by no means the most efficient method it is just a solution that works.
edit: Seen your other question and the code you posted that was this method and yours works much better than this answer
You can get logic by this solution and language use to solve this problem is SWIFT 4.2
var arrColor = ["red","green","blue","green","red","green","blue","green","red","green","blue","green","blue","green","red","green","blue","blue","green","red","green","blue","blue","blue","blue","blue"]
func mostCommonArray(array:[String])->[String]{
var commonArr = [String]()
var dictColor = [String:Int]()
for color in array{
if let count = dictColor[color]{
dictColor[color] = count + 1
}
else{
dictColor[color] = 1
}
}
let highestValue = dictColor.values.max()
for (color,count) in dictColor{
if dictColor[color] == highestValue{
commonArr.append(color)
}
}
return commonArr
}
As the title reads, I have been thinking about creating multiple nested loops that aim to achieve one purpose. Move two generated random numbers between 0-9 through each possible possition of an array.
For example, App generates first number (fNum) 1 and second number (sNum) 6. It then moves these numbers in the array which containts ABC. However firstNum and secondNum will need to also try all the possible combinations, so each one will need to be different with each loop.
-1ABC6
-A1BC6
-AB1C6
-ABC16
-ABC61
-AB6C1
-A6BC1
-6ABC1
-A6B1C
-A61BC
-A16BC
-A1B6C
-A1BC6
and so on...
I beleive the best way will be to create a method for generating a counter, which increments the numbers which I can call.
private int getNextNumber(int num) {
if (num == 0) {
return num;
} else {
num++;
}
if (num < 10) {
return num;
} else {
return -1;
}
}
Then I will need multiple nested loops... I have decided to go for several loops which will go infinitly.
while (j < maxlen) {
//J = 0 and maxlen = length of text so in this case 3 as it is ABC
//Add two numbers and check against answer
while (fNum != -1 || sNum != -1) {
//incrememnt numbers
fNum = getNextNumber(fNum);
System.out.println(fNum);
sNum = getNextNumber(sNum);
System.out.println(fNum);
}
String textIni = "ABC";
int lenOfText = textIni.length();
char[] split = textIni.toCharArray();
for (int i = 0; i < lenOfText; i++) {
//here it will look at the length of the Text and
//try the possible positions it could be at....
//maybe wiser to do a longer loop but I am not too sure
}
}
Since you don't need to store all possible combinations, we will save some memory using only O(n) storage with an iterative solution. I propose you a basic implementation but don't expect to use it on large arrays since it has a O(n³) complexity.
public static void generateCombinationsIterative(List<Integer> original, int fnum, int snum) {
int size = original.size();
for (int i=0 ; i<=size ; i++) {
List<Integer> tmp = new ArrayList<>(original);
tmp.add(i,fnum);
for (int j=0 ; j<=size + 1 ; j++) {
tmp.add(j,snum);
System.out.print(tmp + (i == size && j == size + 1 ? "" : ", "));
tmp.remove(j);
}
}
}
For your culture, here is an example of a recursive solution, which takes a lot of memory so don't use it if you don't need to generate the lists of results. Nevertheless, this is a more general solution that can deal with any number of elements to insert.
public static List<List<Integer>> generateCombinations(List<Integer> original, Deque<Integer> toAdd) {
if (toAdd.isEmpty()) {
List<List<Integer>> res = new ArrayList<>();
res.add(original);
return res;
}
int element = toAdd.pop();
List<List<Integer>> res = new LinkedList<>();
for (int i=0 ; i<=original.size() ; i++)
// you must make a copy of toAdd, otherwise each recursive call will perform
// a pop() on it and the result will be wrong
res.addAll(generateCombinations(insertAt(original,element,i),new LinkedList<>(toAdd)));
return res;
}
// a helper function for a clear code
public static List<Integer> insertAt(List<Integer> input, int element, int index) {
List<Integer> result = new ArrayList<>(input);
result.add(index,element);
return result;
}
Note that I did not use any array in order to benefit from dynamic data structures, however you can call the methods like this :
int[] arr = { 1,2,3 };
int fnum = 4, snum = 5;
generateCombinationsIterative(Arrays.asList(arr),fnum,snum);
generateCombinations(Arrays.asList(arr),new LinkedList<>(Arrays.asList(fnum,snum));
Note that both methods generate the combinations in the same order.
I know my code is a mess and I'm sorry for that, I tried to write it as fast as possible and than to arrange the statements.
it works for most cases but not for {19,17,2,15,6,13,12,7,16,3,22}.
as you can see it should be simple, the array can be sorted in any way, but the even numbers always increase from the beginning to the end, and the odd numbers decrease.
what I tried to do was a regular binary search with some conditions to check if we look at an even or odd number and than adjust accordingly.
Edit: I forgot to mention it's a question I'm trying to solve, they said specifically search the array in the most efficient way.
public static int find(int[] arr,int n)
{
final boolean EVEN;
if (n%2==0)
EVEN = true;
else
EVEN = false;
int min = 0, max = arr.length-1;
int m = 0;
do
{
m = (min+max)/2;
if (n == arr[m])
break;
if (arr[m]%2==0)
{
if (EVEN)
{
if (n>arr[m])
min = m+1;
else
max = m-1;
}
else
{
do
{
m--;
}
while(arr[m]%2==0);
if (arr[m]==n)
break;
if (n>arr[m])
max = m-1;
else
min = m+1;
}
}
else
{
if (!EVEN)
{
if (n>arr[m])
max = m-1;
else
min = m+1;
}
else
{
do
{
m++;
}
while(arr[m]%2!=0);
if (arr[m]==n)
break;
if (n>arr[m])
min = m+1;
else
max = m-1;
}
}
}while(min<max);
if (arr[m]==n)
return m;
else
return -1;
}
Try
while(min<=max);
You might be missing the cases where min and max coincide.
Update:
Yup! I checked it. I ran your program against
int[] array = {19,17,2,15,6,13,12,7,16,3,22};
for all values and it works as expected if you make that correction.