Filtering out ints on an array - java

method takes in an array of ints and returns the new array of ints without even ints. Ive written something up but cannot get the print right in the main method....heres what I have
//filterAway method taking out evens from string
public static int[] filterArray(int[] x){
int [] arrayOne;
int size = 0;
for(int i=0; i<x.length; i++){
if(x[i] % 2 != 0){
size++;
}
}
arrayOne = new int [size];
int index =0;
for(int i=0; i<x.length; i++){
if(x[i] % 2 != 0){
arrayOne[index] = x[1];
index++;
}
}
return arrayOne;
}
//main
public static void main(String args[]){
int[] f = {1,2,3,4,5,6,7,8,9,10,11,12};
for (int i =0; i <f.length; i++){
System.out.print(f[i] + " ");
}
System.out.println(" ");
//here is where im struggling.
int [] fA= (filterAway); // say the string is 1-12....cannot get
// filtered array to print
for (int i =0; i <fA.length; i++){
System.out.print(arrayOne[i] + " ");
}``
System.out.println(" ");
}

Fixing the Display Problem
Try this revised main method, just replace YourClassName with your class name:
public static void main(String args[]) {
int[] f = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12 };
for (int i = 0; i < f.length; i++) {
System.out.print(f[i] + " ");
}
System.out.println(" ");
// here is where im struggling.
int[] fA = YourClassName.filterArray(f);
// filtered array to print
for (int i = 0; i < fA.length; i++) {
System.out.print(fA[i] + " ");
}
System.out.println(" ");
}
However, you'll see you might end up getting something like 2, 2, 2, 2 there. You need to revisit your filterArray function.
Fixing the filterArray function
Since the title of your question is Filtering Out Ints in Java, here's the culprit, change 1 to i, that's why it gives out 2, 2, 2, 2. Also, you want even numbers, so you should look for 0 modulo, change your comparator to ==, instead of !=.

Here's what you should do with your requirements:
package com.sandbox;
public class Sandbox {
public static void main(String[] args) {
int[] all = new int[]{1, 2, 3, 4, 5, 6};
int[] filtered = odds(all);
for (int i : filtered) {
System.out.println(i);
}
}
private static int[] odds(int[] all) {
int sizeOfResult = 0;
for (int i : all) {
if (isOdd(i)) {
sizeOfResult++;
}
}
int[] result = new int[sizeOfResult];
int resultIndex = 0;
for (int i : all) {
if (isOdd(i)) {
result[resultIndex] = i;
resultIndex++;
}
}
return result;
}
private static boolean isOdd(int i) {
return i % 2 != 0;
}
}
Here's what I'd do if I were writing this on my own though: I'd use a List instead of an array, and I'd use CollectionUtils.filter. Here's a snippet of code that will do what you want:
package com.sandbox;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.collections.Predicate;
import java.util.ArrayList;
import java.util.List;
import static com.google.common.primitives.Ints.asList;
public class Sandbox {
public static void main(String[] args) {
List<Integer> result = new ArrayList<Integer>(asList(1, 2, 3, 4, 5, 6));
CollectionUtils.filter(result, new Predicate() {
#Override
public boolean evaluate(Object o) {
return isOdd((Integer) o);
}
});
for (Integer integer : result) {
System.out.println(integer);
}
}
private static boolean isOdd(int i) {
return i % 2 != 0;
}
}

You will need to pass your f[] as an argument to your filterAway() method.
public static void main(String args[]){
int[] f = {1,2,3,4,5,6,7,8,9,10,11,12};
for (int i =0; i <f.length; i++){
System.out.print(f[i] + " ");
}
System.out.println(" ");
int [] fA= filterArray(f);
for (int i =0; i <fA.length; i++){
System.out.print(fA[i] + " ");
}
System.out.println();
}

Related

String Number Addition Java

This is my second week learning Java and I'm trying to implement some functions that I saw in the book I'm studying with.
With the first function I wanted to represent an integer as an array of integer digits so that I can bypass the range of integer values.
For example:
1st Function
Input : integerInput(123456)
Output : integerString[] = {1,2,3,4,5,6}
2nd function
Input : stringInput[] = {123456}
Output : integerString[] = {1,2,3,4,5,6}
3rd function:
(I want to add the 2 integer string values as in like normal addition)
Input : integerString1[] = {1,2,3,4,5,6} integerString2[] = {1,2,3,4,5,6}
Output : [2,4,6,9,1,2]
This is what I have so far, it is full of mistakes and all i could get is an empty output. Would appreciate any help.
Thanks.
public class tryingOut{
public static int[] integerToNumberArray(int value) {
String temp = Integer.toString(value);
int[] list = new int[temp.length()];
for (int i = 0; i < temp.length(); i++) {
list[i] = temp.charAt(i) - '0';
}
return list;
}
public static boolean isNumeric(String value) {
if (value == null) {
return false;
}
try {
int d = Integer.parseInt(value);
} catch (NumberFormatException nfe) {
return false;
}
return true;
}
public static int[] stringToNumberArray(String value) {
boolean checkNumeric = isNumeric(value);
if (checkNumeric = false) {
return null;
} else {
String[] items = value.replaceAll("\\[", "").replaceAll("\\]", "").replaceAll("\\s", "").split(",");
int[] results = new int[items.length];
for (int i = 0; i < items.length; i++) {
try {
results[i] = Integer.parseInt(items[i]);
} catch (NumberFormatException nfe) {
}
}
return results;
}
}
public static int[] addNumberArrays(int[] a1, int[] a2) {
int[] result = null;
return result;
}
public static void main(String[] args) {
int test1 = 19;
int test2 = 823;
int[] list1 = integerToNumberArray(test1);
int[] list2 = integerToNumberArray(test2);
// stringToNumberArray(test1);
// stringToNumberArray(test2);
}
}
Welcome to the world of Programming with JAVA. Firstly, I appreciate your enthusiasm for programming and the efforts you made.
As mentioned in the comments by Basil Bourque you can achieve this by BigInteger. However, I like your interest for trying this yourself and therefore I will try to share a code below with as much description I can provide to make it understable to you.
To point out few mistakes in your original code:
You do not need to handle null separtely with if-condition for your method isNumeric(String value) becaause the try-catch block will automatically handle it for you.
For stringToNumberArray(String value) method you do not need to use the String.split and also it was quite unclear what you did there in line String[] items = ...
Full code:
public class PlayingWithInt {
public static boolean isNumeric(String value) {
try {
Integer.parseInt(value);
} catch (NumberFormatException nfe) {
// This handles both null and other non int values so we don't need an extra condition to check for null
return false;
}
return true;
}
// Assuming argument value is "123456"
public static int[] stringToNumberArray(String value) {
if (isNumeric(value)) { // We generally don't write `== true` or `== false` with boolean values
char[] valueAsCharArray = value.toCharArray(); // valueAsCharArray = {'1', '2', '3', '4', '5', '6'}
int[] valueAsIntArray = new int[valueAsCharArray.length]; // valueAsIntArray = {0, 0, 0, 0, 0, 0}
for (int i = 0; i < valueAsCharArray.length; i++) {
valueAsIntArray[i] = valueAsCharArray[i] - '0';
}
return valueAsIntArray; // valueAsCharArray = {1, 2, 3, 4, 5, 6}
}
return null; // Null will be returned if the value is not numeric
}
// Assuming argument value is {"1", "2", "3", "4", "5", "6"}
public static int[] stringToNumberArray(String[] value) {
int[] valueAsIntArray = new int[value.length]; // valueAsIntArray = {0, 0, 0, 0, 0, 0}
for (int i = 0; i < value.length; i++) {
valueAsIntArray[i] = value[i].charAt(0) - '0';
}
return valueAsIntArray; // valueAsCharArray = {1, 2, 3, 4, 5, 6}
}
// Let's say value is 123456
public static int[] integerToNumberArray(int value) {
String valueAsString = Integer.toString(value); // valueAsString = "123456"
return stringToNumberArray(valueAsString); // We are using our already built method that does the same thing.
}
public static int[] addNumberArrays(int[] a1, int[] a2) {
int maxLength;
if (a1.length > a2.length) maxLength = a1.length;
else maxLength = a2.length;
int[] result = new int[maxLength + 1];
int i = a1.length - 1; // Index iterator for a1
int j = a2.length - 1; // Index iterator for a2
int k = result.length - 1; // Index iterator for result
int carry = 0; // carry to handle case when the sum of two digits more than deci/ ten (10)
while (i >= 0 && j >= 0) {
int sum = a1[i] + a2[j] + carry;
result[k] = sum % 10;
carry = sum / 10;
i--;
j--;
k--;
}
// If a1 has more digits than a2
while (i >= 0) {
int sum = a1[i] + carry;
result[k] = sum % 10;
carry = sum / 10;
i--;
k--;
}
// If a2 has more digits than a1
while (j >= 0) {
int sum = a2[j] + carry;
result[k] = sum % 10;
carry = sum / 10;
j--;
k--;
}
result[0] = carry;
return result;
}
public static void main(String[] args) {
int test1 = 123456;
int test2 = 123456;
int[] num1 = integerToNumberArray(test1);
int[] num2 = integerToNumberArray(test2);
int[] result = addNumberArrays(num1, num2);
for (int i : result) System.out.print(i); // This is known as enhanced-for-loop or for-each-loop
System.out.println();
}
}
Output:
0246912
Additional Input and Output:
Example 1
Code:
public static void main(String[] args) {
int test1 = 19;
int test2 = 823;
int[] num1 = integerToNumberArray(test1);
int[] num2 = integerToNumberArray(test2);
int[] result = addNumberArrays(num1, num2);
for (int i : result) System.out.print(i); // This is known as enhanced-for-loop or for-each-loop
System.out.println();
}
Output:
0842
Example 2
Code:
public static void main(String[] args) {
int test1 = 823;
int test2 = 19;
int[] num1 = integerToNumberArray(test1);
int[] num2 = integerToNumberArray(test2);
int[] result = addNumberArrays(num1, num2);
for (int i : result) System.out.print(i); // This is known as enhanced-for-loop or for-each-loop
System.out.println();
}
Output:
0842
Example 3
Code:
public static void main(String[] args) {
int test1 = 999;
int test2 = 999;
int[] num1 = integerToNumberArray(test1);
int[] num2 = integerToNumberArray(test2);
int[] result = addNumberArrays(num1, num2);
for (int i : result) System.out.print(i); // This is known as enhanced-for-loop or for-each-loop
System.out.println();
}
Output:
1998
References:
String.toCharArray()
Enhanced for-loop |OR| For-Each Loop
Integer.parseInt(String value)

How to replace recursion in my code on Java?

This code calculates the number of permutations for four points by 3 (no repetitions).
Arranged with recursion, but this is awkward for me.
import java.util.*;
public class Main {
static int TOTAL_POINTS = 4, POINTS_ON_LINE = 3;
static int[] temp = new int[POINTS_ON_LINE];
public static void main(String[] args) {
int[] points = new int[]{1,2,3,4};
System.out.println("no repetitions:");
p1(0,0, points);
}
static void p1(int nowPosition, int sizeArray, int[] points) {
if (nowPosition == POINTS_ON_LINE) {
System.out.println("Output:");
System.out.println(Arrays.toString(temp));
} else {
for(int i = sizeArray + 1; i <= TOTAL_POINTS; i++) {
temp[nowPosition] = points[i-1];
p1(nowPosition + 1, i, points);
}
}
}
}
Output:
no repetitions:
Output:
[1, 2, 3]
Output:
[1, 2, 4]
Output:
[1, 3, 4]
Output:
[2, 3, 4]
It is necessary to get rid of the recursive method call p1.
I tried to do so:
import java.util.*;
public class Main {
static int TOTAL_POINTS = 4, POINTS_ON_LINE = 3;
static int[] temp = new int[POINTS_ON_LINE];
public static void main(String[] args) {
int[] points = new int[]{1,2,3,4};
System.out.println("no repetitions:");
p1(points);
}
static void p1(int[] points) {
int sizeArray = points.length;
for(int i = sizeArray + 1; i < TOTAL_POINTS; i++, sizeArray = i) {
int nowPosition = 0;
if(nowPosition == POINTS_ON_LINE) {
System.out.println("Output: " + Arrays.toString(temp));
} else {
temp[nowPosition] = points[i-1];
nowPosition++;
}
}
}
}
Result - Output on console - empty.
It didn't work for me.
How to replace recursion?
Method # 1 (thanks for the suggested option - #deadshot)
package com.company;
import java.util.*;
import java.util.stream.Collectors;
import java.util.stream.IntStream;
public class Main {
static int TOTAL_POINTS = 4, POINTS_ON_LINE = 3;
static int[] temp = new int[POINTS_ON_LINE];
public static void main(String[] args) {
int[] points = new int[]{1, 2, 3, 4};
System.out.println("no repetitions:");
p1(points, POINTS_ON_LINE);
}
public static void p1(int[] arr, int base) {
int SIZE_ARRAY = arr.length;
List<Integer> indices = IntStream.range(0, base).boxed().collect(Collectors.toList());
for(Integer i : indices) {
System.out.println("- " + i);
}
if (base < SIZE_ARRAY) {
System.out.println("first");
System.out.println(indices.stream().map(idx -> arr[idx]).collect(Collectors.toList()));
boolean flag;
int i;
while (true) {
flag = false;
for (i = base - 1; i >= 0; i--)
if (indices.get(i) != i + SIZE_ARRAY - base) {
flag = true;
break;
}
if (!flag)
return;
indices.set(i, indices.get(i) + 1);
for (int j = i + 1; j < base; j++)
indices.set(j, indices.get(j - 1) + 1);
System.out.println(indices.stream().map(idx -> arr[idx]).collect(Collectors.toList()));
for(Integer x : indices) {
System.out.println("- " + x);
}
}
}
}
}
I have used python itertools.combinations code as reference to implement the method.
public class Main {
static int TOTAL_POINTS = 4, POINTS_ON_LINE = 3;
static int[] temp = new int[POINTS_ON_LINE];
public static void main(String[] args) {
int[] points = new int[]{1, 2, 3, 4};
System.out.println("no repetitions:");
p1(points, POINTS_ON_LINE);
}
public static void p1(int[] arr, int r) {
int n = arr.length, i;
int[] indices = new int[r];
for (i = 0; i < r; i++)
indices[i] = i;
if (r < n) {
for (int idx : indices)
temp[idx] = arr[idx];
System.out.println(Arrays.toString(temp));
boolean flag;
while (true) {
flag = false;
for (i = r - 1; i >= 0; i--)
if (indices[i] != i + n - r) {
flag = true;
break;
}
if (!flag)
return;
indices[i] += 1;
for (int j = i + 1; j < r; j++)
indices[j] = indices[j - 1] + 1;
for (i = 0; i < r; i++)
temp[i] = arr[indices[i]];
System.out.println(Arrays.toString(temp));
}
}
}
}

Leetcode : Remove Duplicates from Sorted Array

Why this code is not accepted by Leetcode compiler?
My program is running in netbeans. but leetcode compiler is not accepting it.
Here is my code:
import java.util.Arrays;
public class RemoveDuplicateFromArray {
public static int[] removeDuplicates(int[] nums) {
int temp, count = 0 ,l = 0;
temp = nums[0];
for(int i = 1; i < nums.length - (1 + l); i++ ) {
if(temp == nums[i]) {
count = count + 1;
for(int j = i; j < nums.length - count; j++){
nums[j] = nums[j+1];
}
i = i - 1;
} else {
temp = nums[i];
i = i ;
}
l = count;
}
nums = Arrays.copyOfRange(nums, 0, nums.length-count);
if(nums.length == 2){
if(nums[0] == nums[1]){
nums = Arrays.copyOfRange(nums, 0, nums.length-1);
}
}
return nums;
}
Here is my main mathod:
public static void main(String[] args) {
int[] nums = new int[] {1,1,1}; // showing error here.
System.err.println("nums lenght: " +nums.length);
int new_nums[] = removeDuplicates(nums);
for(int i : new_nums) {
System.err.print(i + " ");
}
}
}
The error is :
incompatible types: int[] cannot be converted to int.
I expect leetcode is having trouble with this line:
int new_nums[] = removeDuplicates(nums);
This isn't the typical way to define an integer array (this is the C style). Java does support the syntax, but it's a little arcane. See this answer for more detail.
Try this instead:
int[] new_nums = removeDuplicates(nums);
Just tried this on LeetCode, seems to work:
I would do it a bit like this myself:
import java.util.ArrayList;
import java.util.List;
public class Main {
public static void main(String[] args) {
int[] nums = new int[]{1, 1, 1, 2, 2, 2, 3, 3, 3, 4, 5, 6, 7, 7, 7, 8, 9, 0, 0, 0, 0};
System.out.println("nums lenght: " + nums.length);
int[] new_nums = removeDuplicates(nums);
for (int i : new_nums) {
System.out.print(i + " ");
}
}
public static int[] removeDuplicates(int[] nums) {
List<Integer> found = new ArrayList();
for (int i = 1; i < nums.length; i++) {
if (!found.contains(nums[i])) {
found.add(nums[i]);
}
}
int[] ret = new int[found.size()];
for(int i = 0; i < found.size(); i++){
ret[i] = found.get(i);
}
return ret;
}
}
public class Solution {
public int removeDuplicates(int[] nums) {
int n = nums.length;
int i = 0;
int j = 1;
if (n <= 1) {
return n;
}
while (j <= n - 1) {
if (nums[i] != nums[j]) {
nums[i + 1] = nums[j];
i++;
}
j++;
}
return i + 1;
}
}
import static org.hamcrest.CoreMatchers.equalTo;
import static org.hamcrest.MatcherAssert.assertThat;
import java.util.Arrays;
import org.junit.jupiter.api.Test;
class SolutionTest {
#Test
void removeDuplicates() {
int[] array = new int[] {1, 1, 2};
int end = new Solution().removeDuplicates(array);
assertThat(Arrays.toString(Arrays.copyOfRange(array, 0, end)), equalTo("[1, 2]"));
}
}

Print Maximum Frequent Element

public class TestClass {
private static int maxOccurence(int a[]) {
int max = 0;
int count = 0;
for (int i = 0; i < a.length - 1; i++) {
for (int j = i + 1; j < a.length; j++) {
if (a[i] == a[j]) {
count++;
max = Math.max(max, count);
}
}
count = 0;
}
return max + 1;
}
public static void main(String[] args) {
int a[] = { 3, 3, 4, 2, 4, 4, 2, 4, 4 };
System.out.println(maxOccurence(a));
}
}
This program counts, for each element of an array, the number of times that the element appears; then, it returns the maximum value. In my example, the program prints "5", since element "4" occurs 5 times. How can the element also be printed? In this case, the output of the program would be "4 : 5".
In Java you can write
int[] a = {3, 3, 4, 2, 4, 4, 2, 4, 4};
Map<Integer, Long> countMap = IntStream.of(a).boxed()
.collect(groupingBy(i -> i, counting()));
Map.Entry<Integer, Long> first = countMap.entrySet().stream()
.sorted(comparing(Map.Entry<Integer, Long>::getValue).reversed())
.findFirst().orElseThrow(AssertionError::new);
System.out.println(first.getKey()+":"+first.getValue());
This prints
4:5
[ANSWERED WHEN TAG WAS C#]
It seems to be a nice solution :
public static class TestClass
{
public static void PrintMaxOccurence(int[] a)
{
var maxOccurenceGroup = a.ToList().GroupBy(s => s)
.OrderByDescending(s => s.Count())
.First();
Console.WriteLine(maxOccurenceGroup.Key + " occured " + maxOccurenceGroup.Count() + " times.");
Console.ReadKey();
}
}
class Program
{
public static void main(String[] args)
{
var a = new[] { 3, 3, 4, 2, 4, 4, 2, 4, 4 };
TestClass.PrintMaxOccurence(a);
}
}
Feel free to ask help if needed.
In C# you have to declare variable as int[] a; but not int a[];
static void Main(string[] args)
{
int[] a = new[] { 3, 3, 4, 2, 4, 4, 2, 4, 4 };
PrintMaxOccurence(a);
}
private static void PrintMaxOccurence(int[] a)
{
var result = (from item in a
group item by item into x
orderby x.Count() descending
select new { Element = x.Key, OccurenceCount = x.Count() }).First();
Console.WriteLine("{0} : {1}", result.Element, result.OccurenceCount);
}
We can as well solve the problem using hashtable as follows.
import java.util.Hashtable;
public class MaxOcurr {
public static void main(String[] args) {
Hashtable<Integer,Integer> table = new Hashtable<Integer, Integer>();
int maxCount = 0;
int maxValue = -1;
int a[] = {1,3,2,5,3,6,8,8,8,6,6,7,5,6,4,5,6,4,6,4,1,3,2,6,9,2};
for (int i = 0; i < a.length; i++) {
if (table.containsKey(a[i])) {
table.put(a[i], table.get(a[i])+1);
} else {
table.put(a[i],1);
}
if (table.get(a[i]) > maxCount) {
maxCount = table.get(a[i]);
maxValue = a[i];
}
}
System.out.println(maxValue +":"+ maxCount);
}
}

Checking one dimensional array for duplicate integers Java

hey guys,
right i have an array of 50 random integers and i have to check if any of them are the same,
here is my code so far it only checks ajacent indexs
for (int i =0; i < 50; i++)
{
System.out.print("Student" + i + ": " );
customers[i] = (int)((Math.random()*10000)%10+1);
System.out.print(" " +customers[i]+ "\n");
if( duplicate == customers[i])
{
System.out.println("yup");
}
duplicate = customers[i];
}
Sort the array first. Then you can check just the next index. If it's ever the same, break.
Okay, I hate ridiculous limitations. If you want, you can do it like this without using a sort:
import java.util.ArrayList;
import java.lang.Math;
public class Main {
public static void main(String[] args) {
ArrayList<Integer> list = new ArrayList<Integer>();
Integer currentValue = 0;
int i = 0;
int limit = 20;
for(i = 0; i < limit; i++) {
list.add((int)(Math.random() * 100));
}
for(i = 0; i < limit; i++) {
currentValue = list.get(i);
list.set(i, -1);
if(list.contains(currentValue)) {
System.out.println("yup:" + currentValue);
return;
} else {
list.set(i, currentValue);
}
}
System.out.println("No duplicates!");
return;
}
}
Is it efficient? No.
Does it work? Yes.
I think, if you have to just use if/for functions, you have to make two loops:
for (int i =0; i < 50; i++)
{
customers[i] = (int)((Math.random()*10000)%10+1);
for ( int j = 0; j < i; j++)
{
if( customers[j] == customers[i])
{
// duplicated entry. do what you want
System.out.println("yup");
}
}
}
You could use Arrays.sort (see more at http://www.exampledepot.com/egs/java.util/coll_SortArray.html) to sort your data, and then check for duplicates.
You use value 0-10 so you can save your value in boolean array and it that way verify if this is duplicate or not:
boolean[] checker = new boolean[11];
for (int i =0; i < 50; i++) {
customers[i] = (int)((Math.random()*10000)%10+1);
if (checker[customers[i]]) {
System.out.println("yup"); //duplication
} else {
checker[customers[i]] = true;
}
}
You can use the below code if you are working with Integer array:
public class DuplicateInteger {
private static int countDuplicate;
public static int[] getDuplicateIntegers(int[] integerArray){
int duplicateIntegers[] = new int[integerArray.length];
countDuplicate = 0;
for(int i=0;i<integerArray.length;i++){
for(int j=i+1;j<integerArray.length;j++){
int replicaTest = 0;
if(integerArray[i]==integerArray[j]){
for(int k=0;k<countDuplicate;k++){
if(duplicateIntegers[k]==integerArray[i]){
replicaTest = 1;
}
}
if(replicaTest==0){
duplicateIntegers[countDuplicate] = integerArray[i];
countDuplicate++;
}
}
}
}
return duplicateIntegers;
}
public static void printDuplicateIntegers(int[] duplicateIntegers){
System.out.println("Duplicate Integers:");
System.out.println("-------------------");
for(int i=0;i<countDuplicate;i++){
System.out.println(duplicateIntegers[i]);
}
}
public static void main(String[] args){
int numberArray[] = {1, 2, 3, 4, 5, 6, 7, 1, 3, 5, 7};
printDuplicateIntegers(getDuplicateIntegers(numberArray));
}
}

Categories

Resources