Trying to only print specific numbers in this Array Method - java

For some reason I have only managed as far as printing the odd numbers, but it somehow still prints what appears to be values that are null. I am trying to only print the values that returned as odd.
public class Odd {
public int[] removeEvens(int [] nums) { //start of method
int [] newArray = new int[nums.length];
int count = 0;
// start of array conversion
for(int i = 0; i < nums.length; i++) {
newArray[count] = nums[i];
count++;
}
int counter = 0;
for (int i = 0; i < nums.length; i++)
if (newArray[i] % 2 == 1)
newArray[counter++] = newArray[i];
for (int i=counter; i < nums.length; i++)
newArray[i] = 0;
return newArray;
}
// end of method
public static void main(String[] args) {
Odd labObject = new Odd();
int [] input = {1,2,3,4,5,6,7,8,9};
int [] result = labObject.removeEvens(input);
// Helper method Arrays.toString() converts int[] to a String
System.out.println(Arrays.toString(result)); // Should print [1, 3, 5, 7, 9]
}
}

change it to return Arrays.copyOfRange(newArray, 0, counter); when you make in array of ints in java with a specified size, it sets every value in the array to 0. Doing this will remove all of the extraneous 0s at the end.

This can be easily solved by working out the correct size of the new array first before you create it. Then simply loop the array and only store the odd numbers. Otherwise, remove/trim the array size before returning it.
Here is a solution by modifying your removeEvens method:
public int[] removeEvens(int[] nums)
{ //start of method
int count = 0;
// start of array conversion
// Count the odd numbers to work out the array length
for (int i = 0; i < nums.length; i++)
{
if (nums[i] % 2 == 1 || nums[i] % 2 == -1)
{
count++;
}
}
// Now create a new array of the correct length
int[] newArray = new int[count];
// Now loop through the original array and only store the odd numbers in the new array
int counter = 0;
for (int i = 0; i < nums.length; i++)
{
if (nums[i] % 2 == 1 || nums[i] % 2 == -1)
{
newArray[counter] = nums[i];
counter ++;
}
}
// Return the result
return newArray;
}
Result:
[1, 3, 5, 7, 9]

Related

How to create an array from a pre-existing array?

New to java and am trying to create a program/method that will take an int array, and return another int array but it replaces the values of the indexes with the value of the elements. (Example {2,1,3} will return {0,0,1,2,2,2}
public static void main(String[] args) {
int[] pracArray = {2, 1, 3};
int sum = 0;
for (int i = 0; i < pracArray.length; i++)
{
sum = sum + pracArray[i];
}
System.out.println("Amount of array indexes: " + sum);
int[] newArray = new int[sum];
System.out.println(Arrays.toString(pracArray));
for (int i = 0; i < pracArray.length; i++)
{
for (int j = 0; j < pracArray[i]; j++)
{
newArray[j] = i;
}
}
System.out.println(Arrays.toString(newArray));
}
}
Currently I am getting [2,2,2,0,0,0]. I have tried changing the how many times each for loop iterates with no avail. I have also tried to make the elements of newArray equal to a counter ( int count = 0; and having count++ in the for loop) since the values of the new array will always be 0 - however many runs.
Given the length of your array is 3, your outer 'i' loop is iterating through the values 0,1,2. That means your inner 'j' loop never writes to index 3,4,5 (hence why they are 0 in the output), and why the first 3 indexes are set to '2' (2 is the last indexed processed in the 'i' loop). Try this instead...
int h = 0;
for (int i = 0; i < pracArray.length; i++)
{
for (int j = 0; j < pracArray[i]; j++)
{
newArray[h] = i;
h++;
}
}

Count how many integers were displayed in an array

I got an 100 random elements array, each element is in range of 0-10, and i need to count each integer how many times it was typed (e.g. 1,2,2,3,8,8,4...)
OUTPUT:
1 - 1
2 - 2
3 - 1
8 - 2
4 - 1
My code so far is:
import java.util.Random;
public class Asses1 {
public static void main(String[] args) {
getNumbers();
}
private static int randInt() {
int max = 10;
int min = 0;
Random rand = new Random();
int randomNum = rand.nextInt((max - min) + 1) + min;
return randomNum;
}
public static int[] getNumbers() {
int number = 100;
int[] array = new int[number];
for (int i = 0; i < array.length; i++) {
System.out.println(randInt());
}
System.out.println(number+" random numbers were displayed");
return array;
}
}
Add this method, which will do the counting:
public static void count(int[] x) {
int[] c=new int[11];
for(int i=0; i<x.length; i++)
c[x[i]]++;
for(int i=0; i<c.length; i++)
System.out.println(i+" - "+c[i]);
}
and change the main into this so that you call the previous method:
public static void main(String[] args) {
count(getNumbers());
}
Also, change the for loop in getNumbers into this in order to fill array with the generated numbers, not just printing them:
for (int i = 0; i < array.length; i++) {
array[i] = randInt();
System.out.println(array[i]);
}
Here is how it can be done in java 8
// Retrieve the random generated numbers
int[] numbers = getNumbers();
// Create an array of counters of size 11 as your values go from 0 to 10
// which means 11 different possible values.
int[] counters = new int[11];
// Iterate over the generated numbers and for each number increment
// the counter that matches with the number
Arrays.stream(numbers).forEach(value -> counters[value]++);
// Print the content of my array of counters
System.out.println(Arrays.toString(counters));
Output:
[12, 11, 7, 6, 9, 12, 8, 8, 10, 9, 8]
NB: Your method getNumbers is not correct you should fix it as next:
public static int[] getNumbers() {
int number = 100;
int[] array = new int[number];
for (int i = 0; i < array.length; i++) {
array[i] = randInt();
}
System.out.println(number+" random numbers were displayed");
return array;
}
int[] array2 = new int[11];
for (int i = 0; i < array.length; i++){
array2[randInt()]++
}
for (int i = 0; i < array.length; i++)
System.out.println(String.valueOf(i) + " - " + String.valueOf(array2[i]));
What I have done is:
Create an helping array array2 for storing number of occurences of each number.
When generating numbers increment number of occurences in helping array.
Map<Integer,Integer> map=new HashMap<Integer,Integer>();
int temp;
for (int i = 0; i < array.length; i++) {
temp=randInt();
if(map.containsKey(temp)){
map.put(temp, map.get(temp)+1);
}else{
map.put(temp, 1);
}
}

Any tips on how to fix my code?

Here is the problem: When given an array arr, return an array which contains only odd integers in the original order from arr.
A Few Examples:
youMakeMeOdd({1,2,3}) ā†’ {1, 3}
youMakeMeOdd({1,3,5}) ā†’ {1, 3, 5}
youMakeMeOdd({2,4,6}) ā†’ {}
And here is my code:
public int [] youMakeMeOdd(int [] arr)
{
int x=0;
for (int i=0; i<arr.length; i++)
{
if (arr[i]%2==1)
{
x++;
}
}
for (int i=0, m=0, j=0; j<x; m++, j++)
{
if (arr[i]%2==1)
{
arr[m]=arr[j];
}
}
return arr;
}
Thank you very much!
Arrays in Java are fixed-size: their length cannot be changed.
So you need to create and return a new array because the result might contain fewer elements.
Determine the size of the output array (count the odd values) to know the length of the result array, then iterate over your input and add the odd numbers to the output.
Example:
public static int[] youMakeMeOdd(int[] arr) {
int count = 0;
for (int n : arr)
if (n % 2 == 1)
count++;
int[] result = new int[count];
int i = 0;
for (int n : arr)
if (n % 2 == 1)
result[i++] = n;
return result;
}

Recursion - Combination with in array with no repetition in Java

So I know how to get the size of a combination - factorial of the size of the array (in my case) over the size of the subset of that array wanted. The issue I'm having is getting the combinations. I've read through most of the questions so far here on stackoverflow and have come up with nothing. I think the issue I'm finding is that I want to add together the elements in the combitorial subsets created. All together this should be done recursively
So to clarify:
int[] array = {1,2,3,4,5};
the subset would be the size of say 2 and combinations would be
{1,2},{1,3},{1,4},{1,5},{2,3},{2,4},{2,5},{3,4},{3,5},{4,5}
from this data I want to see if the subset say... equals 6, then the answers would be:
{1,5} and {2,4} leaving me with an array of {1,5,2,4}
so far I have this:
public static int[] subset(int[] array, int n, int sum){
// n = size of subsets
// sum = what the sum of the ints in the subsets should be
int count = 0; // used to count values in array later
int[] temp = new temp[array.length]; // will be array returned
if(array.length < n){
return false;
}
for (int i = 1; i < array.length; i++) {
for (int j = 0; j < n; j++) {
int[] subset = new int[n];
System.arraycopy(array, 1, temp, 0, array.length - 1); // should be array moved forward to get new combinations
**// unable to figure how how to compute subsets of the size using recursion so far have something along these lines**
subset[i] = array[i];
subset[i+1] = array[i+1];
for (int k = 0; k < n; k++ ) {
count += subset[k];
}
**end of what I had **
if (j == n && count == sum) {
temp[i] = array[i];
temp[i+1] = array[i+1];
}
}
} subset(temp, n, goal);
return temp;
}
How should I go about computing the possible combinations of subsets available?
I hope you will love me. Only thing you have to do is to merge results in one array, but it checks all possibilities (try to run the program and look at output) :) :
public static void main(String[] args) {
int[] array = {1, 2, 3, 4, 5};
int n = 2;
subset(array, n, 6, 0, new int[n], 0);
}
public static int[] subset(int[] array, int n, int sum, int count, int[] subarray, int pos) {
subarray[count] = array[pos];
count++;
//If I have enough numbers in my subarray, I can check, if it is equal to my sum
if (count == n) {
//If it is equal, I found subarray I was looking for
if (addArrayInt(subarray) == sum) {
return subarray;
} else {
return null;
}
}
for (int i = pos + 1; i < array.length; i++) {
int[] res = subset(array, n, sum, count, subarray.clone(), i);
if (res != null) {
//Good result returned, so I print it, here you should merge it
System.out.println(Arrays.toString(res));
}
}
if ((count == 1) && (pos < array.length - 1)) {
subset(array, n, sum, 0, new int[n], pos + 1);
}
//Here you should return your merged result, if you find any or null, if you do not
return null;
}
public static int addArrayInt(int[] array) {
int res = 0;
for (int i = 0; i < array.length; i++) {
res += array[i];
}
return res;
}
You should think about how this problem would be done with loops.
for (int i = 0; i < array.length - 1; i++) {
for (int j = i + 1; j < array.length; j++) {
if (array[i] + array[j] == sum) {
//Add the values to the array
}
}
}
Simply convert this to a recursive code.
The best way I can think to do this would be to have each recursive call run on a subset of the original array. Note that you don't need to create a new array to do this as you are doing in your code example. Just have a reference in each call to the new index in the array. So your constructor might look like this:
public static int[] subset(int[] array, int ind, int sum)
where array is the array, ind is the new starting index and sum is the sum you are trying to find

Printing out the least occurring elements in an array

OK, so I found this question from a few days ago but it's on hold and it won't let me post anything on it.
***Note: The values or order in the array are completely random. They should also be able to be negative.
Someone recommended this code and was thumbed up for it, but I don't see how this can solve the problem. If one of the least occurring elements isn't at the BEGINNING of the array then this does not work. This is because the maxCount will be equal to array.length and the results array will ALWAYS take the first element in the code written below.
What ways are there to combat this, using simple java such as below? No hash-maps and whatnot. I've been thinking about it for a while but can't really come up with anything. Maybe using a double array to store the count of a certain number? How would you solve this? Any guidance?
public static void main(String[] args)
{
int[] array = { 1, 2, 3, 3, 2, 2, 4, 4, 5, 4 };
int count = 0;
int maxCount = 10;
int[] results = new int[array.length];
int k = 0; // To keep index in 'results'
// Initializing 'results', so when printing, elements that -1 are not part of the result
// If your array also contains negative numbers, change '-1' to another more appropriate
for (int i = 0; i < results.length; i++) {
results[i] = -1;
}
for (int i = 0; i < array.length; i++) {
for (int j = 0; j < array.length; j++) {
if (array[j] == array[i]) {
count++;
}
}
if (count <= maxCount) { // <= so it admits number with the SAME number of occurrences
maxCount = count;
results[k++] = array[i]; // Add to 'results' and increase counter 'k'
}
count = 0; // Reset 'count'
}
// Printing result
for (int i : results) {
if (i != -1) {
System.out.println("Element: " + i + ", Number of occurences: " + maxCount);
}
}
}
credit to: https://stackoverflow.com/users/2670792/christian
for the code
I can't thumbs up so I'd just like to say here THANKS EVERYONE WHO ANSWERED.
You can also use an oriented object approach.
First create a class Pair :
class Pair {
int val;
int occ;
public Pair(int val){
this.val = val;
this.occ = 1;
}
public void increaseOcc(){
occ++;
}
#Override
public String toString(){
return this.val+"-"+this.occ;
}
}
Now here's the main:
public static void main(String[] args) {
int[] array = { 1,1, 2, 3, 3, 2, 2, 6, 4, 4, 4 ,0};
Arrays.sort(array);
int currentMin = Integer.MAX_VALUE;
int index = 0;
Pair[] minOcc = new Pair[array.length];
minOcc[index] = new Pair(array[0]);
for(int i = 1; i < array.length; i++){
if(array[i-1] == array[i]){
minOcc[index].increaseOcc();
} else {
currentMin = currentMin > minOcc[index].occ ? minOcc[index].occ : currentMin;
minOcc[++index] = new Pair(array[i]);
}
}
for(Pair p : minOcc){
if(p != null && p.occ == currentMin){
System.out.println(p);
}
}
}
Which outputs:
0-1
6-1
Explanation:
First you sort the array of values. Now you iterate through it.
While the current value is equals to the previous, you increment the number of occurences for this value. Otherwise it means that the current value is different. So in this case you create a new Pair with the new value and one occurence.
During the iteration you will keep track of the minimum number of occurences you seen.
Now you can iterate through your array of Pair and check if for each Pair, it's occurence value is equals to the minimum number of occurences you found.
This algorithm runs in O(nlogn) (due to Arrays.sort) instead of O(nĀ²) for your previous version.
This algorithm is recording the values having the least number of occurrences so far (as it's processing) and then printing all of them alongside the value of maxCount (which is the count for the value having the overall smallest number of occurrences).
A quick fix is to record the count for each position and then only print those whose count is equal to the maxCount (which I've renamed minCount):
public static void main(String[] args) {
int[] array = { 5, 1, 2, 2, -1, 1, 5, 4 };
int[] results = new int[array.length];
int minCount = Integer.MAX_VALUE;
for (int i = 0; i < array.length; i++) {
for (int j = 0; j < array.length; j++) {
if (array[j] == array[i]) {
results[i]++;
}
}
if (results[i] <= minCount) {
minCount = results[i];
}
}
for (int i = 0; i < results.length; i++) {
if (results[i] == minCount) {
System.out.println("Element: " + i + ", Number of occurences: "
+ minCount);
}
}
}
Output:
Element: 4, Number of occurences: 1
Element: 7, Number of occurences: 1
This version is also quite a bit cleaner and removes a bunch of unnecessary variables.
This is not as elegant as Iwburks answer, but I was just playing around with a 2D array and came up with this:
public static void main(String[] args)
{
int[] array = { 3, 3, 3, 2, 2, -4, 4, 5, 4 };
int count = 0;
int maxCount = Integer.MAX_VALUE;
int[][] results = new int[array.length][];
int k = 0; // To keep index in 'results'
for (int i = 0; i < array.length; i++) {
for (int j = 0; j < array.length; j++) {
if (array[j] == array[i]) {
count++;
}
}
if (count <= maxCount) {
maxCount = count;
results[k++] = new int[]{array[i], count};
}
count = 0; // Reset 'count'
}
// Printing result
for (int h = 0; h < results.length; h++) {
if (results[h] != null && results[h][1] == maxCount ) {
System.out.println("Element: " + results[h][0] + ", Number of occurences: " + maxCount);
}
}
Prints
Element: -4, Number of occurences: 1
Element: 5, Number of occurences: 1
In your example above, it looks like you are only using ints. I would suggest the following solution in that situation. This will find the last number in the array with the least occurrences. I assume you don't want an object-oriented approach either.
int [] array = { 5, 1, 2, 40, 2, -1, 3, 2, 5, 4, 2, 40, 2, 1, 4 };
//initialize this array to store each number and a count after it so it must be at least twice the size of the original array
int [] countArray = new int [array.length * 2];
//this placeholder is used to check off integers that have been counted already
int placeholder = Integer.MAX_VALUE;
int countArrayIndex = -2;
for(int i = 0; i < array.length; i++)
{
int currentNum = array[i];
//do not process placeholders
if(currentNum == placeholder){
continue;
}
countArrayIndex = countArrayIndex + 2;
countArray[countArrayIndex] = currentNum;
int count = 1; //we know there is at least one occurence of this number
//loop through each preceding number
for(int j = i + 1; j < array.length; j++)
{
if(currentNum == array[j])
{
count = count + 1;
//we want to make sure this number will not be counted again
array[j] = placeholder;
}
}
countArray[countArrayIndex + 1] = count;
}
//In the code below, we loop through inspecting each number and it's respected count to determine which one occurred least
//We choose Integer.MAX_VALUE because it's a number that easily indicates an error
//We did not choose -1 or 0 because these could be actual numbers in the array
int minNumber = Integer.MAX_VALUE; //actual number that occurred minimum amount of times
int minCount = Integer.MAX_VALUE; //actual amount of times the number occurred
for(int i = 0; i <= countArrayIndex; i = i + 2)
{
if(countArray[i+1] <= minCount){
minNumber = countArray[i];
minCount = countArray[i+1];
}
}
System.out.println("The number that occurred least was " + minNumber + ". It occured only " + minCount + " time(s).");

Categories

Resources