This question already has answers here:
add an element to int [] array in java [duplicate]
(14 answers)
Closed 6 years ago.
How could I add an element to an array?
I could easily simplify my code if I could add an element to an array. My code is shown below.
public int[] intersection(int[] nums1, int[] nums2) {
Arrays.sort(nums1);
Arrays.sort(nums2);
int[] nums2_1 = nums2;
int[] nums2_2 = nums2;
int length = 0;
int number =0;
if ((nums1.length != 0) && (nums2.length != 0)) {
for (int i = 0; i < nums1.length; i++) {
boolean valid = true;
if ((i != 0) && (nums1[i-1] == nums1[i])) {
valid = false;
}
if (binarySearch(nums2_1, nums1[i], 0, nums2.length-1) && valid) {
length++;
}
}
}
int[] nums3 = new int[length];
if ((nums1.length != 0) && (nums2.length != 0)) {
for (int i = 0; i < nums1.length; i++) {
boolean valid = true;
if ((i != 0) && (nums1[i-1] == nums1[i])) {
valid = false;
}
if (binarySearch(nums2_2, nums1[i], 0, nums2.length-1) && valid) {
nums3[number] = nums1[i];
number++;
}
}
}
return nums3;
}
Arrays have a fixed length in Java. If you need to dynamically size your collections of ints, you should consider using one of the implementions of List instead. Then you can add elements to it with the .add() method.
It would look something like this:
List<Integer> nums3 = new ArrayList<Integer>();
and then instead of nums3[number] and keeping track of the number variable, just use
nums3.add(nums1[i]);
Arrays should be used when you know the definite size of the Input. If you do not know the definite size, then its advisable to use the collections framework, based on the usage.
Arrays has fixed size. Easy way to add elements to array is to create another array whose size is old array size + 1. Now add the last element.
Otherwise use ArrayList
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 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.
Given 2 int arrays, a and b, return a new array length 2 containing, as much as will fit, the elements from a followed by the elements from b. The arrays may be any length, including 0, but there will be 2 or more elements available between the 2 arrays.
I'm wondering how to use a !=, and null. This is the first question I've used it in and I'm having a few errors.
So my logic was to iterate through list a, until a null point, then go onto list b.
public int[] make2(int[] a, int[] b) {
int[] answer = new int[2];
for(int x = 0; x <= 1; x++){
if(a[x] != null)
answer[x] = a[x];
else if (b[x != null]){
answer[x] = b[x];
}
}
}
Something like this. Any tips on how to check for emptiness?
else if (b[x != null]){
Is not a valid statement, this will cause an error because (x != null) = true so is the same as else if (b[true]){ which does not make much sense.
Also, an empty array position of int will never be null but zero 0 instead.
Use this instead:
else if (b[x] != 0){
One more thing: as title says, use List to instead of array to have a variable number of elements:
public int[] make2(int[] a, int[] b) {
List<Integer> answers = new ArrayList<Integer>();
for(int x = 0; x <= 1; x++){
if(a[x] != 0) {
answers.add(a[x]);
} else if (b[x] != 0) {
answers.add(b[x]);
}
}
}
NOTES:
use answers instead of answer, is better name for a List with multiple elements.
take as usual to use ALWAYS { even if the statements inside are just one line
your function is not valid since does not include return answer
EDIT
Sorry about the title, my mistake. It is arrays
In this case, just remember arrays are not resizeable, so in the moment of creating the array check maximum size:
int maxSize = a.length > b.length ? a.length : b.length;
int[] answer = new int[maxSize];
NOTE: you can use this variable in your loop to check max number...
EDIT2
An empty array position is represented by a 0? What about the example make2({}, {1, 2}) → {1, 2}, will a[0] != 0 skip it? because index 0 doesn't exist?
you cannot use make2({}, {1, 2}), not a valid statement in this case. To simulate this do:
public static void main(String[] args) {
int a[] = new int[2];
int b[] = new int[2];
b[0] = 1;
b[1] = 2;
make2(a,b);
// if you want to see the output:
System.out.println(Arrays.toString(make2(a,b)));
}
It won't skip it, it will throw an ArrayIndexOutOfBoundsException, in this case, you must make you function failsafe, for this, just check lenghts before accessing the element to assert it will exist:
public static int[] make2(int[] a, int[] b) {
int[] answer = new int[2];
for(int x = 0; x <= 1; x++){
if(a.length >= x && a[x] != 0) {
answer[x] = a[x];
} else if (b.length >= x && b[x] != 0){
answer[x] = b[x];
}
// optional
else {
answer[x] = -1; // this tells you there's no valid element!
}
}
return answer;
}
SOLUTION:
http://www.codingbat.com/prob/p143461 Here is a url to the question :D
Ok, you were missing the examples, all would be much clearer... This code pass all tests.
public int[] make2(int[] a, int[] b) {
int[] answer = new int[2]; // create the array to fill
int y = 0; // create a variable to check SECOND array position
for(int x = 0; x <= 1; x++){ // make 2 iterations
if(a.length > x) { // if ARRAY a has a possible value at POSITION x
answer[x] = a[x]; // put this value into answer
} else if (b.length > y){ // if ARRAY a does not have possible value at POSITION x,
// check if ARRAY b has some possible value at POSITION y
// (remember y is the variable that keeps position of ARRAY b)
answer[x] = b[y++]; // put b value at answer
}
}
return answer; // return answer
}
You can check array if it string but your array is int. so you can use the following example
int arr[] = null;
if (arr != null) {
System.out.println("array is null");
}
arr = new int[0];
if (arr.length != 0) {
System.out.println("array is empty");
}
I have a few questions, before I suggest you some alternatives. 1. why are you declaring int[] answer = new int[2]; when question says 2 or more elements.
You should use :
List<int> stockList = new ArrayList<int>();
if(a[x] != null)
stockList.add(a[x]);
else if (b[x] != null){
stockList.add(b[x]);
}
int[] stockArr = new int[stockList.size()];
stockArr = stockList.toArray(stockArr);
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 have a random set S of integers and the cardinality (n) of this set may vary from 10 to 1000. I need to store all sums of the nCr combinations of size r generated from this set. Usually r range from 3 to 10.
E.g. if S={102,233,344,442,544,613,71289,836,97657,12} and r=4, Then The sums generated will be {0,1,2,3}=102+233+344+442, {0,1,2,4}=102+233+344+544,....so on.
I implemented a findCombi function (below) in Java which gave me all nCr combinations in terms of r sized sets of indices and then I sifted through these sets in another function to generate the sum of corresponding elements.
But the program is giving heapspace error, probably because of exponential nature and I have 100-5000 of such sets, S. Or may be there is a memory leak?
Is there a faster and lesser-memory consuming way to do it?
Note: dsize=n, combiSize=r
List <List<Integer>> findCombi(int dsize,int combiSize) {
if( (combiSize==0) || (dsize==0) ){
return null;
}
long n=dsize;
int r=combiSize;
for(int i=1;i<combiSize;i++) {
n=n*(dsize-i);
r=r*i;
}
int totalcombi=(int) n/r;
List <List<Integer>> combiData=new ArrayList<>(totalcombi);
int pos;
List <Integer> combi=new ArrayList<>(combiSize);
for(int i=0;i<combiSize;i++) {
combi.add(i,i);
}
combiData.add(new ArrayList<>(combi));
pos=combiSize-1;
while(true) {
if(combi.get(pos)<(dsize-combiSize+pos)) {
combi.set(pos,combi.get(pos)+1);
if(pos==(combiSize-1)) {
combiData.add(new ArrayList<>(combi));
}
else {
combi.set(pos+1,combi.get(pos));
pos++;
}
}
else {
pos--;
}
if(pos==-1) {
break;
}
}
return combiData;
}
I needed something like that earlier, so here is some code adapted from the project I made back then. The method allSums builds a list of indices of size r, which is used to represent all the possible combinations. At each step, the current sum is added to the result set, then the next combination is generated. Since the results are put in a set, there is no way a result could appear twice. I included a main method so you can see it work. I hope this is clear, feel free to ask questions.
import java.util.*;
public class Program {
static private Set<Integer> allSums(List<Integer> values, int r) {
HashSet<Integer> res = new HashSet<>();
if ((values.isEmpty()) || r > values.size()) {
return res;
}
// build the list of indices
List<Integer> li = new ArrayList<>();
for (int i = 0; i < r; i++) {
li.add(i);
}
li.add(values.size()); // artificial last index : number of elements in set
while (true) {
// add the current sum to the result
int sum = 0;
for (int i = 0; i < r; i++) {
sum += values.get(li.get(i));
}
res.add(sum);
// move to the next combination
// first, find the last index that can be incremented
int i = r-1;
while ((i >= 0) && (li.get(i) == li.get(i+1)-1)) {
i--;
}
// was such an index found ?
if (i == -1) {
break; // if not, it's over
}
// increment the last index and set all the next indices to their initial value
li.set(i,li.get(i)+1);
for (int j = i+1; j < r; j++) {
li.set(j, li.get(j-1)+1);
}
}
return res;
}
public static void main(String[] args) {
List<Integer> values = new ArrayList<>();
values.add(10);
values.add(100);
values.add(1000);
values.add(10000);
values.add(100000);
Set<Integer> s = allSums(values, 3);
for (int i : s) {
System.out.println(i);
}
}
}