Store results of for loop in array - java

I'm trying to loop through numbers from -6 to 38, and output the odd numbers into an array. I don't know how to store the output into an array.
for (int i = -6; i<38; i++){
if (i%2!=0){
**output to array**
}
}

Because we are not able to know how many the number of the odd numbers is, so you can use IntStream to fix this issue if your java version is 8 or above.
int[] array = IntStream.range(-6, 38).filter(x -> x % 2 != 0).toArray();
Or you can use ArrayList
List<Integer> list = new ArrayList<>();
for (int i = -6; i < 38; i++) {
if (i % 2 != 0) {
list.add(i);
}
}

As the number to elements in array can not be always defined in advance. You can create a list and then convert that to array as below:
List<Integer> oddNumbers = new ArrayList<>();
for (int i = -6; i<38; i++){
if (i%2!=0){
oddNumbers.add(i);
}
}
Integer[] result = oddNumbers.toArray(new Integer[oddNumbers.size()]);

Related

Sort digits of a given integer, without '0'

I'm trying to sort the digits of a given integer by turning the integer to a String and creating an array by the size of that String length.
I'm using the modulu option to separate the digits and in the end I'm reversing it by multiplying by 10.
The problem that it's going out of bound each time and I don't know how to make the size of the array to work good for me.
Here are the code :
String s = String.valueOf(num);
int[] arr = new int[s.length()+1];
while(num != 0) {
arr[(int) num % 10]++;
num = num / 10;
}
long result = 0;
for(int i = 0 ; i < arr.length - 1 ; i++){
for(int j = 0 ; j < arr[i] ; j++) {
result = result * 10;
result = result + i;
}
}
return result;
There seems to be a lot of overkill solving this, as in a lot of code, so here is my take on it.
static int sortDigits(int num) {
char[] arr = Integer.toString(num).toCharArray();
Arrays.sort(arr);
return Integer.parseInt(new String(arr));
}
Test
System.out.println(sortDigits(4201514)); // 112445
You can of course do the same for the long and BigInteger versions:
static long sortDigits(long num) {
char[] arr = Long.toString(num).toCharArray();
Arrays.sort(arr);
return Long.parseLong(new String(arr));
}
static BigInteger sortDigits(BigInteger num) {
char[] arr = num.toString().toCharArray();
Arrays.sort(arr);
return new BigInteger(new String(arr));
}
If I understand your question correctly, when given an integer, you want to "sort" each digit, ignoring 0's.
To do so, so you can first convert it to a string:
String value = String.valueOf(num);
Since you have a string, you can use the split() function to split each 'number' like so:
String[] numbers = value.split("");
Then, you can find the indexes of 0's (and store it somewhere).
ArrayList<Integer> indexes = new ArrayList<>();
for (int i = 0; i < numbers.length; i++) {
if (numbers[i].equals("0")) {
indexes.add(i);
}
}
Then, you can sort the array of strings (numbers) using the sort() function:
Arrays.sort(numbers);
Then, you can remove the 0's like this (by creating a new ArrayList):
ArrayList<String> copy = new ArrayList<>();
for (String s : numbers) {
if (!s.equals("0")) {
copy.add(s);
}
}
(Here, you may use ArrayUtils if you already imported the library.)
Then, concatenate each element to make one entire string with join():
String result = String.join("", copy);
Finally, using the indexes, insert 0's to where they were located at initially:
for (int i : indexes) {
result = result.substring(0, i) + "0" + result.substring(i);
}
result would be what you want.
Note: This might not be the most sufficient way to do it, so you can modify it anywhere you want.
Based on your code I made a few modification
size of array should be 10 since in a number only 0 to 9 digits are possible
use this array to make a frequency array of occurrence of each digit
iterate over the array from 1 to 9 and make a sorted number
public static long sortInt(long num) {
int[] arr = new int[10];
while(num != 0) {
arr[(int) num % 10] ++;
num /= 10;
}
long result = 0;
for(int i = 1 ; i < arr.length ; i++)
while(arr[i]-- != 0)
result = result * 10 + i;
return result;
}

Remove duplicate elements from array along with element in Java 1.7

I need to write a method where a int[] will be supplied as an input and it should return an array, but with all of the numbers that occur more than n times removed entirely.
Inputs:
(int list) data = [1, 2, 2, 3, 3, 3, 4, 5, 5]
Output:
(int list) [1, 4]
These are the steps i have tried.
Copy the int array to ArrayList (inputList).
Create a LinkedHashset to find unique values
Iterate LH and find the collection frequency of ArrayList with iterator.
int[] intArray = new int[0];
if(n!=0){
if(data.length<100){
ArrayList<Integer> inputList = new ArrayList<Integer>(data.length);
//System.out.println(Arrays.toString(data));
for (int i = 0; i < data.length; i++){
inputList.add(Integer.valueOf(data[i]));
}
LinkedHashSet<Integer> lhs = new LinkedHashSet<>(inputList);
intArray = new int[lhs.size()];
int i=0;
int j=0;
Iterator<Integer> itr = lhs.iterator();
while(itr.hasNext()){
Integer shiftNumber = itr.next();
if(Collections.frequency(inputList, shiftNumber)==1) {
intArray[i++] = shiftNumber.intValue();
j++;
}
}
intArray = Arrays.copyOf(intArray, j);
return intArray;
}
}
return intArray;
I am able to achieve the results with the above snippet.However, I need suggestions in reducing the piece of code and improving performance by using any algorithms or other collection objects.
You could use a map instead.
The map key would represent the values found in the array; the map value would be a counter.
You iterate your array, and for each element you either put a counter=1 (when finding that value the first time); or you simply increase that counter.
Finally, you collect only those map keys that show a counter value of 1.
You are likely overcomplicating the algorithm. It might be simpler to just map each value to its frequency and then copy those values with frequency less than n. Also note that you don't need to explicitly covert between int and Integer: Java does it for you automatically.
int[] output = new int[input.length];
Map<Integer,Integer> counts = new HashMap<>();
int size = 0;
for (int i = 0; i < input.length; i++) {
counts.put(input[i], counts.getOrDefault(input[i], 0) + 1);
}
for (int i = 0; i < input.length; i++) {
if (counts.get(input[i]) < n)
output[size++] = input[i];
}
return Arrays.copyOf(output, size);
If you are familiar with Java 8 streams then the code can be substantially reduced:
Map<Integer,Integer> count = Arrays.stream(input).boxed()
.collect(groupingBy(identity(), counting()));
return Arrays.stream(input).filter(i -> count.get(i) < n).toArray();

Java Histogram Array

I have to write a method that takes an array of 30 random integers and returns a new histogram array. The histogram should contain 11 elements with the following contents:
element 0 -- number of elements in the array that are <= 0
1 -- number of elements in the array that are == 1
2 -- number of elements in the array that are == 2
...
9 -- number of elements in the array that are == 9
10 -- number of elements in the array that are >= 10
I'm not sure how to make a histogram using random numbers. I have a method for making a histogram, and a method for making random numbers, but I'm not sure how to combine them.
public static int[] arrayHist(int n) {
int[] a = new int[n];
for (int i = 0; i<a.length; i++) {
a[i] = randomInt (0, 100);
}
return a;
}
public static void printHist() {
int[] scores = new int[30];
int[] counts = new int [100];
for (int i = 0; i<100; i++) {
counts[i] = arrayHist (scores, i, i+1);
}
}
Here is my attempt to calculate a histogram of any given positive integer according to your specification:
public static int[] histogram(int[] scores) {
int[] counts = new int [11];
for (int i = 0; i < scores.length; i++) {
int hist = scores[i] / 10;
if(hist == 0) {
counts[scores[i]]++;
} else {
counts[10] ++;
}
}
return counts;
}
You can pass your array of random numbers to this function. Print the results accordantly.
Basically you have to split your implementation into functions.
Create array of random integer
Calculate the histogram (see my method as example)
Print the histogramm
You mustn't mix this thinks up ;)

Weighted random numbers in 2D Array - Processing

I would like to fill a 3x3 2D array with values 1,2,3.
I need each number to appear for a given times.
For example:
1 to appear 2 times
2 to appear 4 times
3 to appear 3 times
What I need is to store this numbers to array in a random position.
For Example:
1,2,2
3,2,2
1,3,3
I already did this in a simple way using only 2 different numbers controlled by a counter. So I loop through the 2D array and applying random values of number 1 and number 2.
I'm checking if the value is 1 and add it in the counter and the same with number 2. if one of the counter exceeds the number I have set as the maximum appear times then it continues and applies the other value.
Is there any better approach to fill the 3 numbers in random array position?
See code below:
int [][] array = new int [3][3];
int counter1 =0;
int counter2 =0;
for (int i=0; i<3; i++) {
for (int j=0; j<3; j++) {
array[i][j] = (int)random(1, 3); //1,2
if (arrray[i][j]==1) {
counter1++;
} else if (array[i][j] ==2) {
counter2++;
}
//if it is more than 5 times in the array put only the other value
if (counter1>5) {
array[i][j] = 2;
}
//if it is more than 4 times in the array put only the other value
else if (counter2>4) {
array[i][j] = 1;
}
}
}
I finally did this according to this discussion:
How can I generate a random number within a range but exclude some?, with 1D array for tesing, but it does not always works.
Please see attached code:
int []values = new int[28];
int counter1=0;
int counter2=0;
int counter3=0;
for (int i=0; i<values.length; i++) {
if (counter1==14) {
ex = append(ex, 5);
}
if (counter2==4) {
ex =append(ex, 6);
}
if (counter3==10) {
ex =append(ex, 7);
}
values[i] = getRandomWithExclusion(5, 8, ex);
if (values[i]==5) {
counter1++;
} else if (values[i] ==6) {
counter2++;
} else if (values[i] ==7) {
counter3++;
}
}
int getRandomWithExclusion(int start, int end, int []exclude) {
int rand = 0;
do {
rand = (int) random(start, end);
}
while (Arrays.binarySearch (exclude, rand) >= 0);
return rand;
}
I would like to fill the 1D array with values of 5,6 or 7. Each one a specific number. Number 5 can be added 14 times. Number 6 can be added 4 times. Number 7 can be added 10 times.
The above code works most of the times, however somethimes it does not. Please let me know if you have any ideas
This is the Octave/Matlab code for your problem.
n=3;
N=n*n;
count = [1 2; 2 4; 3 3];
if sum(count(:,2)) ~= N
error('invalid input');
end
m = zeros(n, n);
for i = 1:size(count,1)
for j = 1:count(i,2)
r = randi(N);
while m(r) ~= 0
r = randi(N);
end
m(r) = count(i,1);
end
end
disp(m);
Please note that when you address a 2D array using only one index, Matlab/Octave would use Column-major order.
There are a ton of ways to do this. Since you're using processing, one way is to create an IntList from all of the numbers you want to add to your array, shuffle it, and then add them to your array. Something like this:
IntList list = new IntList();
for(int i = 1; i <= 3; i++){ //add numbers 1 through 3
for(int j = 0; j < 3; j++){ add each 3 times
list.append(i);
}
}
list.shuffle();
for (int i=0; i<3; i++) {
for (int j=0; j<3; j++) {
array[i][j] = list.remove(0);
}
}
You could also go the other way: create an ArrayList of locations in your array, shuffle them, and then add your ints to those locations.

Arrays in array, 100 rows, dynamic columns

I'm trying to get this:
arrays[1][0] = 5
arrays[2][0] = 7
arrays[2][1] = 2
arrays[3][0] = 6
arrays[3][1] = 9
arrays[3][2] = 11
So I want arrays[1][] to have one element of random data, arrays[2][] to have 2 elements of random data and so on until I have 100 arrays. So my last array would be arrays[100][] with 100 elements of random data.
This is the code I have now but I get a NullPointerException when arrays[i][j] = generator.nextInt(max) is executed:
Comparable[][] arrays = new Comparable[100][];
for (int i=1; i<101;i++){
for (int j=0; j <= i-1; j++){
arrays[i][j] = generator.nextInt(max);
}
}
Your
Comparable[][] arrays = new Comparable[100][];
line only creates the outermost array. You need to create the arrays that go in it, e.g. something like this:
Comparable[][] arrays = new Comparable[100][];
for (int i=1; i<101;i++){
arrays[i] = new Comparable[/* relevant length here*/]; // <====
for (int j=0; j <= i-1; j++){
arrays[i][j] = generator.nextInt(max);
}
}
It's unclear to me why you start i at 1 or where the randomness should be (I'm guessing at /* relevant length here */), but hopefully that points you the right way.

Categories