I have an array, say
int a[]={2,0,1,0,1,1,0,2,1,1,1,0,1,0,1};
I need to append each of the 5 neighboring elements and assign them to a new array b with length=(a.length/5); and i want to append the 5 neighboring elements so that I have:
int b[]={20101,10211,10101}; I need to do this for various length arrays, in most cases with length of a being greater than 15.
Any help would be greatly appreciated, I'm programming in Java.
Thanks in advance.
It's pretty straighforward:
// Assuming a.length % 5 == 0.
int[] b = new int[a.length / 5];
for (int i = 0; i < a.length; i += 5) {
b[i/5] = a[i]*10000 + a[i+1]*1000 + a[i+2]*100 + a[i+3]*10 + a[i+4];
}
This sounds like a homework question, so I won't give you the complete solution, but the basic rundown is:
Compute the length of b: len = a.length / 5
Construct b with that many elements.
Initialize an index variable to point to the first element in a
For each element in b:
Construct the value for that element from a[idx]...a[idx+4]
Advance the index into a by 5.
Also note that you may need to verify that the input a is actually a multiple of 5 in length.
This works with (a.length % 5) != 0, and keeps leading zeroes (by storing digits into String).
int a[]={2,0,1,0,1,1,0,2,1,1,1,0,1,0,1,0,0,7};
final int N = 5;
String b[] = new String[(a.length + N - 1)/ N];
StringBuilder sb = new StringBuilder(N);
int x = 0;
for (int i = 0; i < b.length; i++) {
sb.setLength(0);
for (int k = 0; k < N && x < a.length; k++) {
sb.append(a[x++]);
}
b[i] = sb.toString();
}
System.out.println(java.util.Arrays.toString(b));
// prints "[20101, 10211, 10101, 007]"
Alternately, you can also use regex:
String[] arr =
java.util.Arrays.toString(a)
.replaceAll("\\D", "")
.split("(?<=\\G.{5})");
System.out.println(java.util.Arrays.toString(arr));
// prints "[20101, 10211, 10101, 007]"
Basically this uses Arrays.toString(int[]) to append all digits into one long String, then removes all non-digits \D, then uses \G-anchored lookbehind to split every .{5}
Naive approach.
import java.util.ArrayList;
/* Naive approach */
public class j2728476 {
public static void main(String[] args) {
int a[] = {2,0,1,0,1,1,0,2,1,1,1,0,1,0,1};
ArrayList<String> al = new ArrayList<String>();
String s = "";
for (int i = 0; i < a.length; i++) {
if (i % 5 == 0 && i != 0) {
al.add(s);
s = "" + a[i];
} else {
s += a[i];
}
}
al.add(s);
for (String t : al) {
// convert values to ints ...
System.out.println(t);
}
}
}
Will print:
20101
10211
10101
import java.util.Arrays;
public class MainClass {
public static void main(String args[]) throws Exception {
int array[] = { 2, 5, -2, 6, -3, 8, 0, -7, -9, 4 };
Arrays.sort(array);
printArray("Sorted array", array);
int index = Arrays.binarySearch(array, 1);
System.out.println("Didn't find 1 # "
+ index);
int newIndex = -index - 1;
array = insertElement(array, 1, newIndex);
printArray("With 1 added", array);
}
private static void printArray(String message, int array[]) {
System.out.println(message
+ ": [length: " + array.length + "]");
for (int i = 0; i < array.length; i++) {
if (i != 0){
System.out.print(", ");
}
System.out.print(array[i]);
}
System.out.println();
}
private static int[] insertElement(int original[],
int element, int index) {
int length = original.length;
int destination[] = new int[length + 1];
System.arraycopy(original, 0, destination, 0, index);
destination[index] = element;
System.arraycopy(original, index, destination, index
+ 1, length - index);
return destination;
}
}
It will print
Sorted array: [length: 10]
-9, -7, -3, -2, 0, 2, 4, 5, 6, 8
Didn't find 1 # -6
With 1 added: [length: 11]
-9, -7, -3, -2, 0, 1, 2, 4, 5, 6, 8
Related
This question already has answers here:
What is the difference between Linear search and Binary search?
(11 answers)
Closed 2 years ago.
Given an array of elements of length N, ranging from 0 to N – 1. All elements may not be present in the array. If element is not present then there will be -1 present in the array. Rearrange the array such that A[i] = i and if i is not present, display -1 at that place
So that is the question, but my binarySearch is not working, why?
for(int i = 0; i < size; i++) {
int res = i;
// System.out.println(Arrays.binarySearch(arr,res));
int result = Arrays.binarySearch(arr,res);
if(result == -1)
arr[i] = -1;
else {
arr[i] = i;
}
}
for(int i = 0; i < size; i++) {
System.out.print(arr[i]+" ");
}
Binary search works only with sorted arrays. Try using a different search algorithm
If you can use additional array, the solution may be as follows:
Create resulting array
Fill resulting array with -1
Iterate over input array and fill appropriate numbers in the resulting array.
// input array
int[] arr = {-1, 2, 3, 0};
// prepare new resulting array
int[] res = new int[arr.length];
// fill with -1
// Arrays.fill(res, -1); // use this shortcut if you're allowed to use library
for (int i = 0; i < res.length; i++) {
res[i] = -1;
}
// rearrange
for (int i = 0; i < arr.length; i++) {
if (arr[i] != -1) {
res[arr[i]] = arr[i];
}
}
System.out.println("input data: " + Arrays.toString(arr));
System.out.println("rearranged: " + Arrays.toString(res));
Output:
input data: [-1, 2, 3, 0]
rearranged: [0, -1, 2, 3]
Update
Recursive solution without using extra array:
public static void test() {
int[] arr = {-1, 4, 2, 0, 1, 3};
System.out.println("input data: " + Arrays.toString(arr));
// rearrange
for (int i = 0; i < arr.length; i++) {
if (arr[i] != -1 && arr[i] != i) {
swapAtIndex(arr, i);
}
}
System.out.println("rearranged: " + Arrays.toString(arr));
}
private static void swapAtIndex(int[] arr, int i) {
int t = arr[i];
if (t != -1 && t != i) {
int t2 = arr[t];
arr[t] = t;
arr[i] = t2;
if (t2 != -1) {
swapAtIndex(arr, i); // continue swapping at the same index
}
}
}
output:
input data: [-1, 4, 2, 0, 1, 3]
rearranged: [0, 1, 2, 3, 4, -1]
For the input array without -1, you'll get a sorted array after rearrangement:
input data: [5, 4, 2, 0, 1, 3]
rearranged: [0, 1, 2, 3, 4, 5]
that, given an array A of N integers, returns the smallest positive integer (greater than 0) that does not occur in A.
For example, given A = [1, 3, 6, 4, 1, 2], the function should return 5.
Given A = [1, 2, 3], the function should return 4.
Given A = [−1, −3], the function should return 1.
Write an efficient algorithm for the following assumptions:
import java.util.*;
class Main {
/* Utility function that puts all non-positive
(0 and negative) numbers on left side of
arr[] and return count of such numbers */
static int segregate(int arr[], int size)
{
int j = 0, i;
for (i = 0; i < size; i++) {
if (arr[i] <= 0) {
int temp;
temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
// increment count of non-positive
// integers
j++;
}
}
return j;
}
/* Find the smallest positive missing
number in an array that contains
all positive integers */
static int findMissingPositive(int arr[], int size)
{
int i;
// Mark arr[i] as visited by making
// arr[arr[i] - 1] negative. Note that
// 1 is subtracted because index start
// from 0 and positive numbers start from 1
for (i = 0; i < size; i++) {
int x = Math.abs(arr[i]);
if (x - 1 < size && arr[x - 1] > 0)
arr[x - 1] = -arr[x - 1];
}
// Return the first index value at which
// is positive
for (i = 0; i < size; i++)
if (arr[i] > 0)
return i + 1; // 1 is added becuase indexes
// start from 0
return size + 1;
}
/* Find the smallest positive missing
number in an array that contains
both positive and negative integers */
static int findMissing(int arr[], int size)
{
// First separate positive and
// negative numbers
int shift = segregate(arr, size);
int arr2[] = new int[size - shift];
int j = 0;
for (int i = shift; i < size; i++) {
arr2[j] = arr[i];
j++;
}
// Shift the array and call
// findMissingPositive for
// positive part
return findMissingPositive(arr2, j);
}
// main function
public static void main(String[] args)
{
int arr[] = { 0, 10, 2, -10, -20 };
int arr_size = arr.length;
int missing = findMissing(arr, arr_size);
System.out.println("The smallest positive missing number is " + missing);
}
}
}
If you need to use stream, the more straightfoward, but not optimal way to do it is to create an infinite stream, starting at 1 and return the first that is not in arr:
int[] arr = { 1, 3, 6, 4, 1, 2 };
Set<Integer> arrSet = Arrays.stream(arr).boxed().collect(Collectors.toSet());
Optional<Integer> found = IntStream.iterate(1, o -> o + 1).boxed()
.filter(value -> !arrSet.contains(value))
.findFirst();
found.ifPresent(System.out::println);
Output
5
As pointed out this is very inefficient, but in terms of computational complexity I believe is optimal, at least for the worst case i.e. the one you have to look at all the elements.
Below you can find the missing positive integer using Streams -
int ar[] = { 0, 10, 2, -10, -20 };
int max = Arrays.stream(ar).max().getAsInt();
System.err.println("maxvalue "+max);
int val = IntStream.range(1, max).filter(i->!Arrays.stream(ar).anyMatch(x->x==i))
.findFirst().getAsInt();
System.out.println(val);
int[] val1 = IntStream.range(1, max).filter(i->!Arrays.stream(ar).anyMatch(x->x==i)).map(p->p).toArray();
System.out.println("------------------");
IntStream.of(val1).forEach(System.out::println);
int[] valEven = IntStream.range(1, max).filter(i->Arrays.stream(val1).anyMatch(x->i%2==0)).map(p->p).toArray();
System.out.println("------------------");
IntStream.of(valEven).forEach(System.out::println);
int[] valOdd = IntStream.range(1, max).filter(i->!Arrays.stream(val1).anyMatch(x->i%2==0)).map(p->p).toArray();
System.out.println("------------------");
IntStream.of(valOdd).forEach(System.out::println);
int[] valOdd1 = IntStream.range(1, max).filter(i->Arrays.stream(val1).noneMatch(x->i%2==0)).map(p->p).toArray();
System.out.println("------------------");
IntStream.of(valOdd1).forEach(System.out::println);
int[] valEven1 = IntStream.range(1, max).filter(i->!Arrays.stream(val1).noneMatch(x->i%2==0)).map(p->p).toArray();
System.out.println("------------------");
IntStream.of(valEven1).forEach(System.out::println);
You can also do a mix of stream and primitive int loop:
import java.util.Arrays;
public class Main {
public static void main(String[] args) {
int[] numberSet1 = {1, 3, 6, 4, 1, 2};
int[] numberSet2 = {-1, -3};
int[] numberSet3 = {1, 2, 3};
System.out.println(calcularPrimero(numberSet1));
System.out.println(calcularPrimero(numberSet2));
System.out.println(calcularPrimero(numberSet3));
}
public static int calcularPrimero (int[] A) {
//IntStream intStream = Arrays.stream(A).filter(x -> x >= 0).distinct().sorted();
int[] B = Arrays.stream(A).filter(x -> x > 0).distinct().sorted().toArray();
for (int i = 0, index = 1; i < B.length; i++, index++) {
if (index != B[i]) {
return index;
}
}
return B.length + 1;
}
}
I have the below question I am trying to solve:
Given an array of integers, return indices of the two numbers such that they add up to a specific target.
I have the below array as input - [2, 7, 11, 15] with target = 9.
Because nums[0] + nums[1] = 2 + 7 = 9,
return [0, 1].
This is my code -
import java.util.Random;
public class TwoSum {
static int[] numbers = new int[] {2, 7, 11, 15};
int[] indices = new int[numbers.length];
public static int[] returnIndices(int target, int[] inputArr) {
int[] indices = new int[2];
int randomOne = new Random().nextInt(inputArr.length);
int randomTwo = new Random().nextInt(inputArr.length);
while(true) {
if(target == inputArr[randomOne] + inputArr[randomTwo]) {
indices[0] = randomOne;
indices[1] = randomTwo;
break;
}
}
System.out.println("done");
return indices;
}
public static void main(String[] args) {
int[] output = returnIndices(9, numbers);
}
}
Is this the right way to approach my problem?
You can use a hashmap to store the first array in the following manner:
key value(index in array)
2 - 0
7 - 1
11 - 2
15 - 3
Next get the target element which is 9, and start traversing your given array from index 0.
Element at index 0 is 2 --> calculate (9-2) = 7 --> check if 7 is a key in the hashmap
Additional Note: You need to take care of the following case:
arr = [3, 2, 1, 1] target = 6 (no answer exists in this case, but by the above method, when you calculate 6-3 = 3 you get index 0 as the answer.)
But this can easily be taken care of by checking whether (target-arr[i] == arr[i]) returns true or not. If it returns true and if the hashmap has two indices stored at the key arr[i], then return it as an answer, else proceed to the next element.
There are various ways to solve this question:
Hashmap way - #mettleap answer has covered that one.
Sort-Array way - I am going to explain its pseudo code to you.
Let us take an example to see it in action first. We are given arr = [5, 2, 1, 9, 7] elements in an array, and we are to find the indices of two elements if we can make 8.
If you look closely, then you will know if we sum 3rd + last element in an array, we will get 8, which means 2 and 4 would be our answer. So How would be land there? Let us go step by step
Maintain a separate array of the same size, it will hold the indices of arr in its initial setup.
[5, 2, 1, 9, 7] = arr
[0, 1, 2, 3, 4] = index_arr
Now sort arr in increasing order, and also sort the index_arr such that index of elements in arr in their initial setup is still in place.
[1, 2, 5, 7, 9] = arr
[2, 1, 0, 4, 3] = index_arr
Use the below pseudo code:
low = 0
high = length of arr - 1
while (low < high) {
sum = arr[low] + arr[high]
if (sum == number) {}
print "index_arr[low]" and "index_arr[high]"
break the loop and exit
} else if ( sum < number ) {
low = low + 1
} else {
high = high - 1
}
}
Let us see psuedo code in action:
[1, 2, 5, 7, 9] = arr
[2, 1, 0, 4, 3] = index_arr
Iteration # 01
low = 0 and high = 4
sum = arr[0] + arr[4] = 1 + 9 = 10
10 > 8 , means 'else' will be executed high = high - 1 = 4 - 1 = 3
Iteration # 02
low = 0 and high = 3
sum = arr[0] + arr[3] = 1 + 7 = 8
8 == 8 , means first 'if' condiion will execute, and will indices and exit the loop
Time Complexity - O(n)
Space Complexity - O(n)
I have tried it in c#, It may help..
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Hello World!");
int[] nums = { 2, 7, 11, 15 };
int target = 9;
int[] result= TwoSumNumbers(nums, target);
}
public static int[] TwoSumNumbers(int[] nums, int target)
{
Dictionary<int, int> numsDict = new Dictionary<int, int>();
for (int i = 0; i < nums.Length; i++)
{
int num = nums[i];
if (numsDict.TryGetValue(target - num, out int index))
{
return new[] { index, i };
}
numsDict[num] = i;
}
return null;
}
}
class Solution {
public int[] twoSum(int[] nums, int target) {
int [] answer = new int[2];
Map<Integer,Integer> values = new HashMap<Integer,Integer>();
for ( int i=0; i < nums.length; i++){
values.put(nums[i],i);
}
for ( int i=0; i < nums.length; i++){
int val = target - nums[i];
Integer secondIndex = values.get(val);
if ( secondIndex != null && secondIndex != i){
answer[0] = i;
answer[1] = secondIndex;
return answer;
}
}
return answer;
}
}
C# Version
using System;
using System.Collections.Generic;
using System.Text;
using System.Linq;
namespace MyBasics
{
class ArrayIndexForTarget
{
public static void Main()
{
ArrayIndexForTarget find = new ArrayIndexForTarget();
int[] arr = new int[] { 9, 2, 3, 9, 10 };
int target = 11;
var result = find.IndexFinder(arr, target);
Console.ReadKey();
}
public int[] IndexFinder(int[]myArray,int target)
{
int[] arr = new int[2];
Dictionary<int, int> dict = new Dictionary<int, int>();
for (int p=0; p < myArray.Length; p++)
{
int numberToFind = target - myArray[p];
if (dict.ContainsValue(numberToFind))
{
arr[0] = dict.FirstOrDefault(x => x.Value == numberToFind).Key;
arr[1] = p;
return arr;
}
else
{
dict.Add(p,myArray[p]);
}
}
return arr;
}
}
}
class Solution {
function twoSum($nums, $target) {
$lenght = count($nums);
$indices = array();
for($i = 0; $i<$lenght-1; $i++){
for($j=$i+1; $j<$lenght; $j++){
if(($nums[$i]+$nums[$j]) == $target){
$indices[] = $i;
$indices[] = $j;
return $indices;
}
}
}
} }
private static int[] findNumbersToAdd(int target, int[] array) {
int[] answer = {-1, -1};
int length = array.length;
for (int i = 0; i < length; i++) {
int var1 = array[i];
for (int j = i + 1; j < length; j++) {
int var2 = array[j];
if (var1 + var2 == target) {
answer[0] = i;
answer[1] = j;
break;
}
}
}
return answer;
}
Given you aren't focused on performance I would think a brute force approach would be fine. Here is a solution using streams and records.
record IndexPair(int index1, int index2) { };
IntStream.range(0, arr.length).boxed()
.flatMap(i1 -> IntStream.range(i1, arr.length)
.filter(i2 -> arr[i1] + arr[i2] == target)
.mapToObj(i2 -> new IndexPair(i1, i2))
.forEach(ip -> ...);
If you only want one solution then you could use findAny instead of forEach.
I tried this question and implement it using HashMap in Java and it works completely fine.
public class Solution {
public int[] twoSum(final int[] A, int B) {
HashMap<Integer,Integer> hm=new HashMap<>();
int index1=Integer.MAX_VALUE;
int index2=Integer.MAX_VALUE;
int diff=0;
for(int i=0;i<A.length;i++){
diff=B-A[i];
if(hm.containsKey(diff)){
index2=i;
index1=hm.get(diff);
return new int[] {index1+1,index2+1};
}else{
if(!hm.containsKey(A[i])){
hm.put(A[i],i);
}
}
}
// If Arrays doesnt have such pairs
if(index2 == (Integer.MAX_VALUE) || index1 == (Integer.MAX_VALUE)){
return new int[] {};
}
return new int[] {index1+1,index2+1};
}
}
here is a simple solution with 2 running loops,
assuming the following
you only need 2 numbers to get to the target.
the solution exists (therefor no need to validate).
public int[] TwoSum(int[] nums, int target) {
for (int i=0; i< nums.Length; i++){
for (int j=i+1; j< nums.Length; j++){
if (nums[i] + nums[j] == target){
return new int[]{i,j};
}
}
}
return null;
}
public int[] sumofTwo(int[] numbers, int target)
{
int[] answer = new int[2];
Map<Integer,Integer> map = new HashMap<Integer,Integer>();
for(int i = 0 ; i < numbers.length ; i++)
{
if(map.containsKey(target - numbers[i]))
{
answer[0] = map.get(target - numbers[i]);
answer[1] = i;
return answer;
}
else
{
map.put(numbers[i],i);
}
}
return null;
}
}
public class Main {
public static void main(String[] args) {
int [] arr = {4,7,1,-3,2};
for(int i=0; i<arr.length-1; i++)
{
for(int j=0; j<=arr.length-2; j++)
{
if((arr[i]+arr[j+1])==6)
{
System.out.println("indices = "+"["+i +","+(j+1)+"]");
}
}
}
}
}
Need assistance with programming issue.
Must be in Java. Cannot use any libraries (Arraylist, etc.).
int[] a = {1, 2, 3, 4, 8, 5, 7, 9, 6, 0}
int[] b = {0, 2, 11, 12, 5, 6, 8}
Have to create an object referencing these two arrays in a method that merges them together, removes duplicates, and sorts them.
Here's my sort so far. Having difficulty combining two arrays and removing duplicates though.
int lastPos;
int index;
int temp;
for(lastPos = a.length - 1; lastPos >= 0; lastPos--) {
for(index = 0; index <= lastPos - 1; index++) {
if(a[index] > a[index+1]) {
temp = a[index];
a[index] = a[index+1];
a[index+1] = temp;
}
}
}
a method that merges them together, removes duplicates, and sorts them.
I suggest you break this down into helper methods (and slightly tweak the order of operations). Step 1, merge the two arrays. Something like,
static int[] mergeArrays(int[] a, int[] b) {
int[] c = new int[a.length + b.length];
for (int i = 0; i < a.length; i++) {
c[i] = a[i];
}
for (int i = 0; i < b.length; i++) {
c[a.length + i] = b[i];
}
return c;
}
Step 2, sort the new array (your existing sort algorithm is fine). Like,
static void sortArray(int[] a) {
for (int lastPos = a.length - 1; lastPos >= 0; lastPos--) {
for (int index = 0; index <= lastPos - 1; index++) {
if (a[index] > a[index + 1]) {
int temp = a[index];
a[index] = a[index + 1];
a[index + 1] = temp;
}
}
}
}
Finally, remove duplicates. Step 3a, count unique values. Assume they're unique, and decrement by counting adjacent (and equal) values. Like,
static int countUniqueValues(int[] c) {
int unique = c.length;
for (int i = 0; i < c.length; i++) {
while (i + 1 < c.length && c[i] == c[i + 1]) {
i++;
unique--;
}
}
return unique;
}
Then step 3b, take the unique count and build your result with the previous methods. Like,
public static int[] mergeDedupSort(int[] a, int[] b) {
int[] c = mergeArrays(a, b);
sortArray(c);
int unique = countUniqueValues(c);
int[] d = new int[unique];
int p = 0;
for (int i = 0; i < c.length; i++) {
d[p++] = c[i];
while (i + 1 < c.length && c[i] == c[i + 1]) {
i++;
}
}
return d;
}
Then you can test it with your arrays like
public static void main(String[] args) {
int[] a = { 1, 2, 3, 4, 8, 5, 7, 9, 6, 0 };
int[] b = { 0, 2, 11, 12, 5, 6, 8 };
int[] c = mergeDedupSort(a, b);
System.out.println(Arrays.toString(c));
}
And I get
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 11, 12]
Merge Two Arrays without Duplicates and Sort it (No libraries used).
Using an object.
public class MergeRemoveDupSort {
public int[] mergeRemoveDupSortIt(int[] a, int[] b) {
int [] c = mergeIt(a,b);
int [] d = removeIt(c);
int [] e = sortIt(d);
return e;
}
private int[] mergeIt(int[] a, int[] b) {
int[] c = new int[a.length + b.length];
int k=0;
for (int n : a) c[k++]=n;
for (int n : b) c[k++]=n;
return c;
}
private int[] removeIt(int[] c) {
int len=c.length;
for (int i=0;i<len-1;i++)
for (int j=i+1;j<len;j++)
if (c[i] == c[j]) {
for (int k=j;k<len-1;k++)
c[k]=c[k+1];
--len;
}
int [] r = new int[len];
for (int i=0;i<r.length;i++)
r[i]=c[i];
return r;
}
private int[] sortIt(int[] a) {
for(int index=0; index<a.length-1; index++)
for(int i=index+1; i<a.length; i++)
if(a[index] > a[i]){
int temp = a[index];
a[index] = a[i];
a[i] = temp;
}
return a;
}
public void printIt(int[] a) {
System.out.print("[");
for (int i=0;i<a.length;i++){
System.out.print(a[i]);
if (i!=a.length-1) System.out.print(",");
else System.out.print("]");
}
}
public static void main(String[] args) {
int[] a = {1, 2, 3, 4, 8, 5, 7, 9, 6, 0};
int[] b = {0, 2, 11, 12, 5, 6, 8};
MergeRemoveDupSort array = new MergeRemoveDupSort();
int [] r = array.mergeRemoveDupSortIt(a, b);
array.printIt(r);
}
}
You should use IntStream like this.
int[] a = {1, 2, 3, 4, 8, 5, 7, 9, 6, 0};
int[] b = {0, 2, 11, 12, 5, 6, 8};
int[] merged = IntStream
.concat(IntStream.of(a), IntStream.of(b))
.distinct()
.sorted()
.toArray();
System.out.println(Arrays.toString(merged));
Assuming that array a and array b are sorted, the following code will merge them into a third array merged_array without duplicates :
public static int[] get_merged_array(int[] a, int[] b, int a_size, int b_size)
{
int[] merged_array = new int[a_size + b_size];
int i = 0 , j = 0, x = -1;
for(; i < a_size && j < b_size;)
{
if(a[i] <= b[j])
{
merged_array[++x] = a[i];
++i;
}
else
{
if(merged_array[x] != b[j])
{
merged_array[++x] = b[j]; // avoid duplicates
}
++j;
}
}
--i; --j;
while(++i < a_size)
{
merged_array[++x] = a[i];
}
while(++j < b_size)
{
merged_array[++x] = b[j];
}
return merged_array;
}
Hope this may help, all the best :)
try{
int[] a = {1, 2, 3, 4, 8, 5, 7, 9, 6, 0};
int[] b = {0, 2, 11, 12, 5, 6, 8};
int[] c = new int[a.length+b.length];
int[] final = new int[a.length+b.length];
int i = 0;
for(int j : final){
final[i++] = -1;
}
i = 0;
for(int j : a){
c[i++] = j;
}
for(int j : b){
c[i++] = j;
}
boolean check = false;
for(int j = 0,k = 0; j < c.length; j++){
for(int l : fin){
if( l == c[j] )
check = true;
}
if(!check){
final[k++] = c[j];
} else check = false;
}
} catch(Exception ex){
ex.printStackTrace();
}
I prefer you to use Hashset for this cause it never allow duplicates
and there is another method in java 8 for arraylist to remove duplicates
after copying all elements to c follow this code
List<Integer> d = array.asList(c);
List<Integer> final = d.Stream().distinct().collect(Collectors.toList());
final.forEach(System.out::println());
This code is lot much better than previous one and you can again transform final to array like this
int array[] = new int[final.size()];
for(int j =0;j<final.size();j++){
array[j] = final.get(j);
}
Hope my work will be helpful .
Let me restate your question.
You want a program that takes two arbitrary arrays, merges them removing any duplicates, and sorts the result.
First of all, if you have access to any data structure, there are much better ways of doing this. Ideally, you would use something like a TreeSet.
However, assuming all you have access to is arrays, your options are much more limited. I'm going to go ahead and assume that each of the two arrays initially has no duplicates.
Let's assume the first array is of length m and the second array is of length n.
int[] array1; // length m
int[] array2; // length n
First, let's sort both arrays.
Arrays.sort(array1);
Arrays.sort(array2);
This assumes you have access to the Arrays class which is part of the standard Java Collections Framework. If not, any reasonable merge implementation (like MergeSort) will do the trick.
The sorts will take O(n log n + m log m) with most good sort implementations.
Next, let's merge the two sorted arrays. First, we need to allocate a new array big enough to hold all the elements.
int[] array3 = new int[size];
Now, we will need to insert the elements of array1 and array2 in order, taking care not to insert any duplicates.
int index=0, next=0, i=0, j=0;
int last = Integer.MAX_INT;
while(i < m || j < n) {
if(i == m)
next = array2[j++];
else if(j == n)
next = array1[i++];
else if(array1[i] <= array2[j])
next = array1[i++];
else
next = array2[j++];
if(last == next)
continue;
array3[index++] = next;
}
Now, you have your array. Just one problem - it could have invalid elements at the end. One last copy should take care of it...
int[] result = Arrays.copyOf(array3, index + 1);
The inserts and the final copy will take O(n + m), so the overall efficiency of the algorithm should be O(n log n + m log n).
As a part of the Java interview question paper I have got following issue to solve.
But I am bit wonder whether how can I implement it without any Collection or intermediate Array.
Question:- Count duplicates from int array without using any Collection or another intermediate Array
Input values:- {7,2,6,1,4,7,4,5,4,7,7,3, 1}
Output:- Number of duplicates values: 3
Duplicates values: 7, 4, 1
I have implemented following solution but was not completed one.
Any one has some idea? Thanks.
public static void duplicate(int numbers[]) {
for (int i = 0; i < numbers.length; i++) {
boolean duplicate = false;
int j = 0;
while (j < i){
if ((i != j) && numbers[i] == numbers[j]) {
duplicate = true;
}
j++;
}
if (duplicate) {
System.out.print(numbers[i] + " ");
}
}
}
The easiest way to solve this problem is to sort the array first, and then just walk through the array counting duplicates as you encounter them:
int[] numbers = new int[]{7,2,6,1,4,7,4,5,4,7,7,3,1};
int temp = 0;
// I chose to do a bubble sort of the array,
// but you are free to use any method you wish (e.g. Arrays.sort)
System.out.print("Duplicates values: ");
for (int i=0; i < numbers.length; ++i) {
for (int j=1; j < (numbers.length - i); ++j) {
if (numbers[j-1] > numbers[j]) {
temp = numbers[j-1];
numbers[j-1] = numbers[j];
numbers[j] = temp;
}
}
}
// walk through the sorted array and count duplicates
int numDup = 0, dupCount = 0;
int previous = -1;
for (int i=0; i < numbers.length; ++i) {
if (numbers[i] == previous) {
++numDup;
if (numDup == 1) {
++dupCount;
if (dupCount == 1) {
System.out.print(numbers[i]);
}
else {
System.out.print(", " + numbers[i]);
}
}
}
else {
previous = numbers[i];
numDup = 0;
}
}
System.out.println("\nNumber of duplicates values: " + dupCount);
Output:
Duplicates values: 1, 4, 7
Number of duplicates values: 3
Note that my output order is reverse of what you have, because you need to read through the entire array before you know how many total duplicates you have. Also, I will point out that the only state this solution uses is the input array itself, plus a couple of int varibles here and there.
This code has been tested in IntelliJ and it works correctly.
Agreed to Tim #tim-biegeleisen. Just minor change. Use the Arrays to sort the array.
import java.util.*;
public class DuplicateClass {
public static void main(String[] args) {
int[] values = { 7, 2, 6, 1, 4, 7, 4, 5, 4, 7, 7, 3, 1 };
duplicate(values);
}
public static void duplicate(int numbers[]) {
Arrays.sort(numbers);
int previous = numbers[0] - 1;
int dupCount = 0;
for (int i = 0; i < numbers.length; ++i) {
if (numbers[i] == previous) {
++dupCount;
} else {
previous = numbers[i];
}
}
System.out.println("There were " + dupCount + " duplicates in the array.");
}
}
These are all great answers. One other is to use an int/double and set it's bits when you encounter a number. This works if the array's values are less than 32/64 depending on the type you use.
Below is an example of how you would do that with an integer.
public class SetThoseBits{
// 0000 0000 0000 0000 000 0000 0000 0000
public static int data = 0;
public static void main(String [] args){
// Gurantee that the numbers are less than 32
int[] values = { 7, 2, 6, 1, 4, 7, 4, 5, 4, 7, 7, 3, 1 };
duplicates(values);
}
public static void duplicates(int [] values){
for(int i : values){
if(testBit(i)){
System.out.println("Duplicate :" + i);
} else{
setBit(i);
}
//printBits();
}
System.out.println("Finished!");
}
// Sets the bit at a specific position
public static void setBit(int index){
data = data | (1 << index);
}
// This function will test the bit at the index of the given integer
// If it's set, it returns true
public static boolean testBit(int index){
return ((data & (1 << index)) != 0);
}
public static void printBits(){
for (int x = 31; x >= 0; x--){
if(testBit(x)){
System.out.print("1");
} else{
System.out.print("0");
}
}
System.out.println("0");
}
}
I believe the the other answers are better given your question..but demonstrating this as an alternative shows that you're thinking about it dynamically. If the requirements of the question changed a little this answer might be more appropriate.
Further if you only need to keep track of duplicates given the smallest footprint possible, you could do something similar to what is above or use java's BitSet class to make your life easier.
http://docs.oracle.com/javase/7/docs/api/java/util/BitSet.html
Edit: It is also possible to have values higher than 64 given that you create a function that holds an array of bytes like the BitSet class. For this exact question this isn't helpful given the constraint to not use an array or collection.
private static int solution3(List<Integer> inputArr) {
// Time Complexity O(N)
// Space Complexity O(1)
// Stream
return (int) inputArr.stream()
.collect(Collectors
.toMap(Function.identity(), v -> 1, Integer::sum))
.entrySet().stream()
.filter(k -> k.getValue() >= 2)
.count();
}
Keeping one extra variable for maintaining count, plus sorting of array in the initial phase.
public static void main(String[] args) {
int[] numbers = { 7, 2, 6, 1, 4, 7, 4, 5, 4, 7, 7, 3, 1 };
Arrays.sort(numbers);
System.out.println("Sorted Array is :: = " + Arrays.toString(numbers));
int count = 0;
int tempCount = 0; // to keep local count of matched numbers
String duplicates = "";
for (int i = 1; i < numbers.length; i++) {
if (numbers[i] == numbers[i - 1]) {
if ((tempCount == 0)) { // If same number is repeated more than
// two times, like 444, 7777
count = count + 1;
tempCount = tempCount + 1;
duplicates = duplicates.concat(Integer.toString(numbers[i])
+ ",");
}
} else {
tempCount = 0;
}
}
System.out.println("No of duplicates :: = " + count);
System.out.println("Duplicate Numbers are :: = " + duplicates);
}
output
Sorted Array is :: = [1, 1, 2, 3, 4, 4, 4, 5, 6, 7, 7, 7, 7]
No of duplicates :: = 3
Duplicate Numbers are :: = 1,4,7,
int numbers[]={7,2,6,1,4,7,4,5,4,7,7,3, 1};
String temp="";
int count=0;
Arrays.sort(numbers);
for (int i = 0; i < numbers.length; i++) {
boolean duplicate = false;
for(int j = 0; j < numbers.length; j++) {
if ((i != j) && numbers[i] == numbers[j]) {
duplicate = true;
}
}
if (duplicate) {
if(!temp.contains(""+numbers[i]))
{
temp+=numbers[i]+", ";//adding a number if its duplicate
count++;//counting unique duplicate number
}
System.out.print(numbers[i] + " ");
}
}
System.out.println("\nDuplicates are: "+temp+" count: "+count);
Output:
Duplicates are: 1, 4, 7, count: 3
I think, this is also a way to calculate it:
public class App {
public static void main(String[] args) {
Integer[] intArr = { 7, 2, 6, 1, 4, 7, 4 };
List<Integer> listInt = Arrays.asList(intArr);
Map<Integer, Integer> map = new HashMap<>();
Integer dupCount = 0;
StringBuilder dupvalues = new StringBuilder();
for (Integer integer : intArr) {
int times = Collections.frequency(listInt, integer);
if (map.containsKey(integer)) {
dupvalues.append(integer).append(",");
dupCount++;
} else
map.put(integer, times);
}
System.out.println("There were " + dupCount + " duplicates in the array. The value are : "+dupvalues);
}
}
This is the simplest solution I can think of. I just added an extra counter so that integers with two or more repetitions still in the array are ignored.
static int findNumber(int[] arr)
{
int duplicateCounter = 0;
System.out.print("Duplicates: ");
for(int i = 0; i < arr.length; i++)
{
boolean duplicate = false;
int numOfOccurrences = 1;
for (int j = (i+1); j < arr.length; j++)
{
if (arr[i] == arr[j])
{
numOfOccurrences++;
duplicate = true;
}
}
if(numOfOccurrences == 2 && duplicate == true)
{
duplicateCounter++;
System.out.print(arr[i] + " ");
}
}
return duplicateCounter;
}
My test run: Test run
Input: 1, 2, 3, 4, 2, 4, 1, 1, 1
Duplicates: 2 4 1
Number of duplicates: 3
Below method not use any collection, just use Arrays.sort() method to help sort array into ascending order as default, e.g array = [9,3,9,3,9] will sort into [3,3,9,9,9].If input [9,9,9,9,9], expected result is 1, since only repeated number is 9.If input [9,3,9,3,9,255,255,1], expected result is 3, since repeated numbers are 3,9,255. If input [7,2,6,1,4,7,4,5,4,7,7,3,1], expected result is 3, since repeated numbers are 1,4,7.
public static int findDuplicateCountsInArray(int[] nums) {
// Sort the input array into default ascending order
Arrays.sort(nums);
int prev = nums[0];
int count = 0;
// Recording a number already a repeated one
// e.g [9,9,9] the 3rd 9 will not increase duplicate count again
boolean numAlreadyRepeated = false;
for(int i = 1; i < nums.length; i++) {
if(prev == nums[i] && !numAlreadyRepeated) {
count++;
numAlreadyRepeated = true;
} else if(prev != nums[i]) {
prev = nums[i];
numAlreadyRepeated = false;
}
}
return count;
}
Here I have written code in JAVA. also the inputted numbers, have been considered as String. This question has also been added to CODEWARS. and I hope this simple solution helps You
public class countingduplicates {
public static void main(String[] args) {
int i=0,j=0,c=0,a=0;
String text="7261474547731";
text=text.toLowerCase();
for(i=0; i<text.length(); i++) {
for(j=0; j<text.length(); j++) {
if(text.charAt(i) == text.charAt(j)) {
c++;
}
}
System.out.println(text.charAt(i) + " occured " + c + " times");
if(c>1) {
a++;
}
String d = String.valueOf(text.charAt(i)).trim();
text = text.replaceAll(d,"");
c = 0;
i = 0; //cause i have trimmed the string and by default i increases by 1, so i have to assign it =0
j = 0; //cause i have trimmed the string and by default j increases by 1, so i have to assign it =0
}
System.out.println("Total count of Duplicates:" + a);
}
}
This is practically very easy in Python. You can check this code. I am giving you 2 methods. Please take a look at it.
array = ['a','b','c','d','a','b','c','d','e']
array1 = [1,2,2,3,3,3,4,5,6,4,4,5,5,5,5]
output = {i : array1.count(i) for i in array1 }
print(output) #{1: 1, 2: 2, 3: 3, 4: 3, 5: 5, 6: 1}
output2 = dict(Counter(array1))
print(output2) #{1: 1, 2: 2, 3: 3, 4: 3, 5: 5, 6: 1}
If you want only the Duplicate numbers, then :
#method 1
output = [k for k,v in Counter(array1).items() if v>1 ]
print(output)
If you want only the Distinct numbers, then :
#method 1
#Prints only Distinct absolute values
O2 = set([abs(i) for i in array1])
print(O2) #1,2,3,4,5,6