Combinations of integers - java

I'd appreciate any help on the following problem. I have n integers from 0 to n-1, and I'm trying to generate a list of all possible combinations of length k (i.e. k concatenated integers) such that every pair of consecutive integers are not equal. So, for example, (1)(2)(3)(2) would be valid with k = 4, but (1)(2)(3)(3) would not be valid. Any ideas on how to approach this most efficiently? (I don't care much about length/degree of complexity of the code, just efficiency)

It is the code:
void Generate(int[] source, List<int[]> result, int[] build, int k, int num) {
if (num == k) {
int[] a = (int[])build.clone();
result.add(a);
return;
}
for (int i = 0; i < source.length; i++)
if (num == 0 || source[i] != build[num - 1])
{
build[num] = source[i];
Generate(source, result, build, k, num + 1);
}
}
How to call:
int k = 2;
List<int[]> a = new ArrayList<int[]>();
Generate(new int[]{1,2,3}, a, new int[k], k, 0);

public class Generator {
final int k = 2;
final char[] n = new char[]{'0','1','2','3','4','5','6','7','8','9'};
final char[] text = new char[k];
public void gen(int i, int not_n) {
if(i == k) {
System.out.println(text);
return;
}
for(int j = 0; j < n.length; j++) {
if(j == not_n) continue;
text[i] = n[j];
gen(i+1, j);
}
}
public static void main(String[] args) {
new Generator().gen(0, -1);
}
}

public static void recursiveOutput(Integer n, int k, int limit, String prints){
k++;
if(k>limit)
return;
String statePrints = prints;
//cycle through all available numbers
for(Integer i = 1; i<=n; i++)
{
statePrints = prints;
//First cycle
if(k==1){
statePrints+= "(" + i.toString() + ")";
recursiveOutput(n, k, limit, statePrints);
}
//check if predecessor is not the same
if(i != Integer.parseInt(statePrints.substring(statePrints.length()-2,statePrints.length()-1))){
statePrints += "(" + i.toString() + ")";
recursiveOutput(n, k, limit, statePrints);
}
}
//Check if the length matches the combination length
if(statePrints.length() == 3 * limit)
System.out.println(statePrints);
}
call :recursiveOutput(3,0,4,"");

Related

Java finding the smallest integer in a speciofic position in a sets of integer

Algorithm:
Procedure SELECT( k,S)
{ if ISI =1 then return the single element in S
else { choose an element a randomly from S;
let S1,S2,and S3 be he sequences of elements in S
less than, equal to, and greater than m, respectively;
if IS1I >=k then return SELECT(k,S1)
else
if (IS1I + IS2I >=k then return m
else return SELECT(k-IS1I-IS2I , S3);
}
}
The question is to implement the first algorithm for finding the kth smallest integer in a set of integers and test your program for different sets of integers generated by a random number generator.
Below is my solution.
import java.util.Random;
import java.util.Scanner;
public class main {
private static Random rand = new Random();
private static Scanner keyboard = new Scanner(System.in);
public static int firstAlgorithm(int k, int[] S) {
int m = S[rand.nextInt(S.length)];
int[] S1 = new int[S.length];
int[] S2 = new int[S.length];
int[] S3 = new int[S.length];
int p = 0;
int q = 0;
int r = 0;
if (S.length == 1)
return S[0];
for (int i = 0; i < S.length; i++) {
if (S[i] < m) {
S1[p] = S[i];
p++;
} else if (S[i] == m) {
S2[q] = S[i];
q++;
} else {
S3[r] = S[i];
r++;
}
}
S1 = trimToSize(S1, p);
S2 = trimToSize(S2, q);
S3 = trimToSize(S3, r);
if (S1.length >= k)
return firstAlgorithm(k, S1);
else if (S1.length + S2.length >= k)
return m;
else
return firstAlgorithm(k - S1.length - S2.length, S3);
}
private static int[] trimToSize(int[] arr, int size) {
int[] temp = new int[size];
for (int i = 0; i < size; i++) {
temp[i] = arr[i];
}
return temp;
}
public static void printArray(int[] S) {
for (int i = 0; i < S.length; i++) {
System.out.print(S[i] + "\t");
if (i % 10 == 9)
System.out.println();
}
}
// start main method
public static void main(String[] args) {
System.out.print("Enter the size of an array: ");
int size = keyboard.nextInt();
while (size < 1) {
System.out.println("Size of the array should be greater than 0.");
System.out.print("Enter the size of an array: ");
size = keyboard.nextInt();
}
System.out.print("Enter the value of k: ");
int k = keyboard.nextInt();
while (k < 1 || k > size) {
System.out.println("Value of k should be in the range 1-" + size + ".");
System.out.print("Enter the value of k: ");
k = keyboard.nextInt();
}
int[] S = new int[size];
for (int i = 0; i < size; i++) {
S[i] = 100 + rand.nextInt(900);
}
System.out.println("\nRandom values generated in the array:");
printArray(S);
System.out.println();
System.out.println(k + "th smallest value in the array using Algorithm #1: " + firstAlgorithm(k, S));
}
}
But I need to implement the above algorithm without using a temporary array for partitioning. How can I do it?
The algorithm is Dijkstra's 3-way partition.
You will have to modify the original S.
Untested (pseudo) code ahead
public static int partition(int left, int right, int[] S) {
int m = rand.nextInt(right-left); // protect against malicious data
swap(S[left+m], S[right]);
int equal = left;
while (left < right) {
if (a[left] < a[n])
swap(S, left++, equal++)
else if (a[left] == a[n])
swap(S, left, --right);
else
left++;
}
return left, equal;
}
public static int firstAlgorithm(int k, int left, int right, int[] S) {
if (left == right)
return S[left];
int p, e = partition(left, right, S); // returns 2 values. S1=[0,p), S2=[p,e), S3=[e, n)
if (p >= k)
return firstAlgorithm(k, left, p, S);
else if (e >= k) // p < k
return S[p]; // p is the first equal, e is first larger than equal
else // e < k
return firstAlgorithm(k, e, right, S);
}
// test
S = {1, 4, 2, 6, 2};
k = 2;
int result = firstAlgorithm(2, 0, S.length-1, S);
assert(result == 2);
Warning syntax and off-by-one errors guarantied.
See here multiple ways to return 2 values in java.

Is there a test case scenario in which my program will fail?

Problem : You have L, a list containing some digits (0 to 9). Write a function solution(L) which finds the largest number that can be made from some or all of these digits and is divisible by 3. If it is not possible to make such a number, return 0 as the solution. L will contain anywhere from 1 to 9 digits. The same digit may appear multiple times in the list, but each element in the list may only be used once.
Test Cases :
Input:
Solution.solution({3, 1, 4, 1})
Output: 4311
Input:
Solution.solution({3, 1, 4, 1, 5, 9})
Output: 94311
My Program :
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Comparator;
import java.util.stream.IntStream;
public class Solution {
static ArrayList<Integer> al = new ArrayList<Integer>();
static ArrayList<Integer> largest = new ArrayList<Integer>();
static int o = 1;
static int po = 0;
static void combinations(String[] digits, String[] data, int start, int end, int index, int r)
{
if (index == r)
{
String temp = "0";
for (int j = 0; j < r; j++)
{
temp = temp + data[j];
// System.out.print(data[j]);
}
Integer d = Integer.parseInt(temp);
al.add(d);
// System.out.println(al);
}
for (int i = start; i <= end && ((end - i + 1) >= (r - index)); i++)
{
data[index] = digits[i];
combinations(digits, data, i + 1, end, index + 1, r);
}
}
static void printCombinations(String[] sequence, int N)
{
String[] data = new String[N];
for (int r = 0; r < sequence.length; r++)
combinations(sequence, data, 0, N - 1, 0, r);
}
static String[] convert(int[] x)
{
String c[] = new String[x.length];
for(int i=0; i < x.length; i++)
{
Integer k = x[i];
if(k==0)
{
o = o * 10;
continue;
}
c[i] = k.toString();
}
// System.out.println(o);
c = Arrays.stream(c).filter(s -> (s != null && s.length() > 0)).toArray(String[]::new);
po = c.length;
// System.out.println("Come"+ Arrays.asList(c));
return c;
}
public static int solution(int[] l) {
if(l.length==0)
return 0;
if(IntStream.of(l).sum()%3==0)
{
String x = "";
Arrays.sort(l);
for (int i = l.length - 1; i >= 0; i--) {
x = x + l[i];
}
return Integer.parseInt(x);
}
printCombinations(convert(l),po);
al.sort(Comparator.reverseOrder());
al.remove(al.size()-1);
al.removeIf( num -> num%3!=0);
if(al.isEmpty())
return 0;
for(int i=0; i< al.size(); i++)
{
Integer n = al.get(i);
printMaxNum(n);
}
// System.out.println(al);
// System.out.println(largest);
return largest.get(0)*o;
}
static void printMaxNum(int num)
{
// hashed array to store count of digits
int count[] = new int[10];
// Converting given number to string
String str = Integer.toString(num);
// Updating the count array
for(int i=0; i < str.length(); i++)
count[str.charAt(i)-'0']++;
// result is to store the final number
int result = 0, multiplier = 1;
// Traversing the count array
// to calculate the maximum number
for (int i = 0; i <= 9; i++)
{
while (count[i] > 0)
{
result = result + (i * multiplier);
count[i]--;
multiplier = multiplier * 10;
}
}
// return the result
largest.add(result);
}
public static void main(String[] args) {
System.out.println(solution(new int[]{9,8,2,3}));
}
}
My Code passes both given test cases and 3 other hidden test cases except one. I tried all possible input combinations but couldn't get to the exact failure. The return type by default is given as int and therefore they would not pass values which give output that does not fit in int. Any other scenario where my code fails?

What is the most efficient algorithm to find repeated elements in an array in time complexity O(n) and space complexity O(1)?

Note-You can not use Collection or Map
I have tried this but this is not having complexity O(n)
class RepeatElement
{
void printRepeating(int arr[], int size)
{
int i, j;
System.out.println("Repeated Elements are :");
for (i = 0; i < size; i++)
{
for (j = i + 1; j < size; j++)
{
if (arr[i] == arr[j])
System.out.print(arr[i] + " ");
}
}
}
public static void main(String[] args)
{
RepeatElement repeat = new RepeatElement();
int arr[] = {4, 2, 4, 5, 2, 3, 1};
int arr_size = arr.length;
repeat.printRepeating(arr, arr_size);
}
}
Is any one having solution for solving,to find a duplicate array without using Collection or Map and using only single for loop
If the elements in an array with size n are in a range of 0 ~ n-1 ( or 1 ~ n).
We can try to sort the array by putting a[i] to index i for every a[i] != i, and if we find that there is already an a[i] at index i, it means that there is another element with value a[i].
for (int i = 0; i < a.length; i++){
while (a[i] != i) {
if (a[i] == a[a[i]]) {
System.out.print(a[i]);
break;
} else {
int temp = a[i]; // Putting a[i] to index i by swapping them
a[i] = a[a[i]];
a[temp] = temp;
}
}
}
Since after every swap, one of the elements will be in the right position, so there will be at most n swap operations.
Time complexity O(n)
Space complexity O(1)
As these are ints, you could use a BitSet:
void printRepeating(int arr[], int size) {
BitSet bits = new BitSet();
BitSet repeated = new BitSet();
//to deal with negative ints:
BitSet negativeBits = new BitSet();
BitSet negativeRepeatedBits = new BitSet();
for(int i : arr) {
if(i<0) {
i = -i; //use the absolute value
if(negativeBits.get(i)) {
//this is a repeat
negativeRepeatedBits.set(i);
}
negativeBits.set(i);
} else {
if(bits.get(i)) {
//this is a repeat
repeated.set(i);
}
bits.set(i);
}
}
System.out.println(
IntStream.concat(negativeRepeatedBits.stream().map(i -> -i), repeated.stream())
.mapToObj(String::valueOf)
.collect(Collectors.joining(", ", "Repated Elements are : ", ""))
);
}
Note that (as per comment) negative values need to be treated separately, as otherwise you could be faced with IndexOutOfBoundsException.
Ok, so you have a constant memory requirement for an array of type int?
No problem, just let's use a large (but constant) byte array:
byte[] seen = new byte[536870912];
byte[] dups = new byte[536870912];
for (int i : arr) {
int idx = i / 8 + 268435456;
int mask = 1 << (i % 8);
if ((seen[idx] & mask) != 0) {
if ((dups[idx] & mask) == 0) {
System.out.print(i + " ");
dups[idx] |= mask;
}
} else {
seen[idx] |= mask;
}
}
As we only iterate once over the array, we have a time complexity of O(n) (where n is the number of elements in the array).
And because we always use the same amount of space we have a memory complexity of O(1), that is independent of anything.
Just one for loop, i will increment when j is at the end of the array, the current arr[i] is found earlier of a new duplicate element is found
void printRepeatingSingleLoop(int arr[], int size)
{
int i, j, k;
System.out.println("Repeated Elements are :");
for (i = 0, j = 1, k = 0; i < size; )
{
if (k < i ) {
if (arr[i] == arr[k]) {
i++;
j = i+1;
k = 0;
} else {
k++;
}
} else {
if (j == size) {
i++;
j = i + 1;
k = 0;
} else {
if (arr[i] == arr[j]) {
System.out.print(arr[i] + " ");
i++;
j = i + 1;
k = 0;
} else {
j++;
}
}
}
}
System.out.println();
}

Java - Rotating array

So the goal is to rotate the elements in an array right a times.
As an example; if a==2, then array = {0,1,2,3,4} would become array = {3,4,0,1,2}
Here's what I have:
for (int x = 0; x <= array.length-1; x++){
array[x+a] = array[x];
}
However, this fails to account for when [x+a] is greater than the length of the array. I read that I should store the ones that are greater in a different Array but seeing as a is variable I'm not sure that's the best solution.
Thanks in advance.
Add a modulo array length to your code:
// create a newArray before of the same size as array
// copy
for(int x = 0; x <= array.length-1; x++){
newArray[(x+a) % array.length ] = array[x];
}
You should also create a new Array to copy to, so you do not overwrite values, that you'll need later on.
In case you don't want to reinvent the wheel (maybe it's an exercise but it can be good to know), you can use Collections.rotate.
Be aware that it requires an array of objects, not primitive data type (otherwise you'll swap arrays themselves in the list).
Integer[] arr = {0,1,2,3,4};
Collections.rotate(Arrays.asList(arr), 2);
System.out.println(Arrays.toString(arr)); //[3, 4, 0, 1, 2]
Arraycopy is an expensive operation, both time and memory wise.
Following would be an efficient way to rotate array without using extra space (unlike the accepted answer where a new array is created of the same size).
public void rotate(int[] nums, int k) { // k = 2
k %= nums.length;
// {0,1,2,3,4}
reverse(nums, 0, nums.length - 1); // Reverse the whole Array
// {4,3,2,1,0}
reverse(nums, 0, k - 1); // Reverse first part (4,3 -> 3,4)
// {3,4,2,1,0}
reverse(nums, k, nums.length - 1); //Reverse second part (2,1,0 -> 0,1,2)
// {3,4,0,1,2}
}
public void reverse(int[] nums, int start, int end) {
while (start < end) {
int temp = nums[start];
nums[start] = nums[end];
nums[end] = temp;
start++;
end--;
}
}
Another way is copying with System.arraycopy.
int[] temp = new int[array.length];
System.arraycopy(array, 0, temp, a, array.length - a);
System.arraycopy(array, array.length-a, temp, 0, a);
I think the fastest way would be using System.arrayCopy() which is native method:
int[] tmp = new int[a];
System.arraycopy(array, array.length - a, tmp, 0, a);
System.arraycopy(array, 0, array, a, array.length - a);
System.arraycopy(tmp, 0, array, 0, a);
It also reuses existing array. It may be beneficial in some cases.
And the last benefit is the temporary array size is less than original array. So you can reduce memory usage when a is small.
Time Complexity = O(n)
Space Complexity = O(1)
The algorithm starts with the first element of the array (newValue) and places it at its position after the rotation (newIndex). The element that was at the newIndex becomes oldValue. After that, oldValue and newValue are swapped.
This procedure repeats length times.
The algorithm basically bounces around the array placing each element at its new position.
unsigned int computeIndex(unsigned int len, unsigned int oldIndex, unsigned int times) {
unsigned int rot = times % len;
unsigned int forward = len - rot;
// return (oldIndex + rot) % len; // rotating to the right
return (oldIndex + forward) % len; // rotating to the left
}
void fastArrayRotation(unsigned short *arr, unsigned int len, unsigned int rotation) {
unsigned int times = rotation % len, oldIndex, newIndex, length = len;
unsigned int setIndex = 0;
unsigned short newValue, oldValue, tmp;
if (times == 0) {
return;
}
while (length > 0) {
oldIndex = setIndex;
newValue = arr[oldIndex];
while (1) {
newIndex = computeIndex(len, oldIndex, times);
oldValue = arr[newIndex];
arr[newIndex] = newValue;
length--;
if (newIndex == setIndex) { // if the set has ended (loop detected)
break;
}
tmp = newValue;
newValue = oldValue;
oldValue = tmp;
oldIndex = newIndex;
}
setIndex++;
}
}
int[] rotate(int[] array, int r) {
final int[] out = new int[array.length];
for (int i = 0; i < array.length; i++) {
out[i] = (i < r - 1) ? array[(i + r) % array.length] : array[(i + r) % array.length];
}
return out;
}
The following rotate method will behave exactly the same as the rotate method from the Collections class used in combination with the subList method from the List interface, i.e. rotate (n, fromIndex, toIndex, dist) where n is an array of ints will give the same result as Collections.rotate (Arrays.asList (n).subList (fromIndex, toIndex), dist) where n is an array of Integers.
First create a swap method:
public static void swap (int[] n, int i, int j){
int tmp = n[i];
n[i] = n[j];
n[j] = tmp;
}
Then create the rotate method:
public static void rotate (int[] n, int fromIndex, int toIndex,
int dist){
if(fromIndex > toIndex)
throw new IllegalArgumentException ("fromIndex (" +
fromIndex + ") > toIndex (" + toIndex + ")");
if (fromIndex < toIndex){
int region = toIndex - fromIndex;
int index;
for (int i = 0; i < dist % region + ((dist < 0) ? region : 0);
i++){
index = toIndex - 1;
while (index > fromIndex)
swap (n, index, --index);
}
}
}
Java solution wrapped in a method:
public static int[] rotate(final int[] array, final int rIndex) {
if (array == null || array.length <= 1) {
return new int[0];
}
final int[] result = new int[array.length];
final int arrayLength = array.length;
for (int i = 0; i < arrayLength; i++) {
int nIndex = (i + rIndex) % arrayLength;
result[nIndex] = array[i];
}
return result;
}
For Left Rotate its very simple
Take the difference between length of the array and number of position to shift.
For Example
int k = 2;
int n = 5;
int diff = n - k;
int[] array = {1, 2, 3, 4, 5};
int[] result = new int[array.length];
System.arraycopy(array, 0, result, diff, k);
System.arraycopy(array, k, result, 0, diff);
// print the output
Question : https://www.hackerrank.com/challenges/ctci-array-left-rotation
Solution :
This is how I tried arrayLeftRotation method with complexity o(n)
looping once from k index to (length-1 )
2nd time for 0 to kth index
public static int[] arrayLeftRotation(int[] a, int n, int k) {
int[] resultArray = new int[n];
int arrayIndex = 0;
//first n-k indexes will be populated in this loop
for(int i = k ; i
resultArray[arrayIndex] = a[i];
arrayIndex++;
}
// 2nd k indexes will be populated in this loop
for(int j=arrayIndex ; j<(arrayIndex+k); j++){
resultArray[j]=a[j-(n-k)];
}
return resultArray;
}
package com.array.orderstatistics;
import java.util.Scanner;
public class ArrayRotation {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
int n = scan.nextInt();
int r = scan.nextInt();
int[] a = new int[n];
int[] b = new int[n];
for (int i = 0; i < n; i++) {
a[i] = scan.nextInt();
}
scan.close();
if (r % n == 0) {
printOriginalArray(a);
} else {
r = r % n;
for (int i = 0; i < n; i++) {
b[i] = a[(i + r) < n ? (i + r) : ((i + r) - n)];
System.out.print(b[i] + " ");
}
}
}
private static void printOriginalArray(int[] a) {
for (int i = 0; i < a.length; i++) {
System.out.print(a[i] + " ");
}
}
}
Following routine rotates an array in java:
public static int[] rotateArray(int[] array, int k){
int to_move = k % array.length;
if(to_move == 0)
return array;
for(int i=0; i< to_move; i++){
int temp = array[array.length-1];
int j=array.length-1;
while(j > 0){
array[j] = array[--j];
}
array[0] = temp;
}
return array;
}
You can do something like below
class Solution {
public void rotate(int[] nums, int k) {
if (k==0) return;
if (nums == null || nums.length == 0) return;
for(int i=0;i<k;i++){
int j=nums.length-1;
int temp = nums[j];
for(;j>0;j--){
nums[j] = nums[j-1];
}
nums[0] = temp;
}
}
}
In the above solution, k is the number of times you want your array to rotate from left to right.
Question : Rotate array given a specific distance .
Method 1 :
Turn the int array to ArrayList. Then use Collections.rotate(list,distance).
class test1 {
public static void main(String[] args) {
int[] a = { 1, 2, 3, 4, 5, 6 };
List<Integer> list = Arrays.stream(a).boxed().collect(Collectors.toList());
Collections.rotate(list, 3);
System.out.println(list);//[4, 5, 6, 1, 2, 3]
}// main
}
I use this, just loop it a times
public void rotate(int[] arr) {
int temp = arr[arr.length - 1];
for(int i = arr.length - 1; i > 0; i--) {
arr[i] = arr[i - 1];
}
arr[0] = temp;
}

Finding closest number to 0

I have an array of integers, and I need to find the one that's closest to zero (positive integers take priority over negative ones.)
Here is the code I have so far:
public class CloseToZero {
public static void main(String[] args) {
int[] data = {2,3,-2};
int curr = 0;
int near = data[0];
// find the element nearest to zero
for ( int i=0; i < data.length; i++ ){
curr = data[i] * data[i];
if ( curr <= (near * near) ) {
near = data[i];
}
}
System.out.println( near );
}
}
Currently I'm getting a result of -2 but I should be getting 2. What am I doing wrong?
This will do it in O(n) time:
int[] arr = {1,4,5,6,7,-1};
int closestIndex = 0;
int diff = Integer.MAX_VALUE;
for (int i = 0; i < arr.length; ++i) {
int abs = Math.abs(arr[i]);
if (abs < diff) {
closestIndex = i;
diff = abs;
} else if (abs == diff && arr[i] > 0 && arr[closestIndex] < 0) {
//same distance to zero but positive
closestIndex =i;
}
}
System.out.println(arr[closestIndex ]);
If you are using java8:
import static java.lang.Math.abs;
import static java.lang.Math.max;
public class CloseToZero {
public static void main(String[] args) {
int[] str = {2,3,-2};
Arrays.stream(str).filter(i -> i != 0)
.reduce((a, b) -> abs(a) < abs(b) ? a : (abs(a) == abs(b) ? max(a, b) : b))
.ifPresent(System.out::println);
}
}
Sort the array (add one line of code) so the last number you pick up will be positive if the same absolute value is selected for a positive and negative numbers with the same distance.
Source code:
import java.util.Arrays;
public class CloseToZero {
public static void main(String[] args) {
int[] data = {2,3,-2};
int curr = 0;
int near = data[0];
Arrays.sort(data); // add this
System.out.println(Arrays.toString(data));
// find the element nearest to zero
for ( int i=0; i < data.length; i++ ){
System.out.println("dist from " + data[i] + " = " + Math.abs(0 -data[i]));
curr = data[i] * data[i];
if ( curr <= (near * near) ) {
near = data[i];
}
}
System.out.println( near );
}
}
Just add zero to this list.
Then sort the list
Arrays.sort(data);
then grab the number before or after the zero and pick the minimum one greater than zero
Assumption is that the array data has at least 1 value.
int closestToZero = 0;
for ( int i = 1; i < data.length; i++ )
{
if ( Math.abs(data[i]) < Math.abs(data[closestToZero]) ) closestToZero = i;
}
The value in closestToZero is the index of the value closest to zero, not the value itself.
static int Solve(int N, int[] A){
int min = A[0];
for (int i=1; i<N ; i++){
min = min > Math.abs(0- A[i]) ? Math.abs(0- A[i]) : Math.abs(min);
}
return min;
}
As you multiply data[i] with data[i], a value negative and a value positive will have the same impact.
For example, in your example: 2 and -2 will be 4. So, your code is not able to sort as you need.
So, here, it takes -2 as the near value since it has the same "weight" as 2.
I have same answer with different method,Using Collections and abs , we can solved.
static int Solve(int N, int[] A){
List<Integer> mInt=new ArrayList<>();
for ( int i=0; i < A.length; i++ ){
mInt.add(Math.abs(0 -A[i]));
}
return Collections.min(mInt);
}
That all,As simple as that
This is a very easy to read O(n) solution for this problem.
int bigestNegative = Integer.MIN_VALUE;
int smalestpositive = Integer.MAX_VALUE;
int result = 0;
for (int i = 0; i < n; i++) {
//if the zero should be considered as result as well
if ( temperatures[i] == 0 ) {
result = 0;
break;
}
if ( temperatures[i] > 0 && temperatures[i] < smalestpositive ) {
smalestpositive = temperatures[i];
}
if ( temperatures[i] < 0 && temperatures[i] > bigestNegative ) {
bigestNegative = temperatures[i];
}
}
if( (Math.abs(bigestNegative)) < (Math.abs(smalestpositive)) && bigestNegative != Integer.MIN_VALUE)
result = bigestNegative;
else
result = smalestpositive;
System.out.println( result );
First convert the int array into stream. Then sort it with default sorting order. Then filter greater than zero & peek the first element & print it.
Do it in declarative style which describes 'what to do', not 'how to do'. This style is more readable.
int[] data = {2,3,-2};
IntStream.of(data)
.filter(i -> i>0)
.sorted()
.limit(1)
.forEach(System.out::println);
using Set Collection and abs methode to avoid complex algo
public static void main(String[] args) {
int [] temperature={0};
***// will erase double values and order them from small to big***
Set<Integer> s= new HashSet<Integer>();
if (temperature.length!=0) {
for(int i=0; i<temperature.length; i++) {
***// push the abs value to the set***
s.add(Math.abs(temperature[i]));
}
// remove a zero if exists in the set
while(s.contains(0)) {
s.remove(0);
}
***// get first (smallest) element of the set : by default it is sorted***
if (s.size()!=0) {
Iterator iter = s.iterator();
System.out.println(iter.next());
}
else System.out.println(0);
}
else System.out.println(0);
}
static int nearToZero(int[] A){
Arrays.sort(A);
int ans = 0;
List<Integer> list = Arrays.stream(A).boxed().collect(Collectors.toList());
List<Integer> toRemove = new ArrayList<>();
List<Integer> newList = new ArrayList<>();
for(int num: list){
if(newList.contains(num)) toRemove.add(num);
else newList.add(num);
}
list.removeAll(toRemove);
for(int num : list){
if(num == 0 ) return 0;
if(ans == 0 )ans = num;
if(num < 0 && ans < num) ans = num;
if(num < ans) ans = num;
if(num > 0 && Math.abs(ans) >= num) ans = num;
}
return ans;
}
here is a method that gives you the nearest to zero.
use case 1 : {1,3,-2} ==> return 1 : use the Math.abs() for comparison and get the least.
use case 2 : {2,3,-2} ==> return 2 : use the Math.abs() for comparison and get the Math.abs(least)
use case 3 : {-2,3,-2} ==> return -2: use the Math.abs() for comparison and get the least.
public static double getClosestToZero(double[] liste) {
// if the list is empty return 0
if (liste.length != 0) {
double near = liste[0];
for (int i = 0; i < liste.length; i++) {
// here we are using Math.abs to manage the negative and
// positive number
if (Math.abs(liste[i]) <= Math.abs(near)) {
// manage the case when we have two equal neagative numbers
if (liste[i] == -near) {
near = Math.abs(liste[i]);
} else {
near = liste[i];
}
}
}
return near;
} else {
return 0;
}
}
You can do like this:
String res = "";
Arrays.sort(arr);
int num = arr[0];
int ClosestValue = 0;
for (int i = 0; i < arr.length; i++)
{
//for negatives
if (arr[i] < ClosestValue && arr[i] > num)
num = arr[i];
//for positives
if (arr[i] > ClosestValue && num < ClosestValue)
num = arr[i];
}
res = num;
System.out.println(res);
First of all you need to store all your numbers into an array. After that sort the array --> that's the trick who will make you don't use Math.abs(). Now is time to make a loop that iterates through the array. Knowing that array is sorted is important that you start to make first an IF statement for negatives numbers then for the positives (in this way if you will have two values closest to zero, let suppose -1 and 1 --> will print the positive one).
Hope this will help you.
The easiest way to deal with this is split the array into positive and negative sort and push the first two items from both the arrays into another array. Have fun!
function closeToZeroTwo(arr){
let arrNeg = arr.filter(x => x < 0).sort();
let arrPos = arr.filter(x => x > 0).sort();
let retArr = [];
retArr.push(arrNeg[0], arrPos[0]);
console.log(retArr)
}
Easiest way to just sort that array in ascending order suppose input is like :
int[] array = {10,-5,5,2,7,-4,28,65,95,85,12,45};
then after sorting it will gives output like:
{-5,-4,2,5,7,10,12,28,45,65,85,95,}
and for positive integer number, the Closest Positive number is: 2
Logic :
public class Closest {
public static int getClosestToZero(int[] a) {
int temp=0;
//following for is used for sorting an array in ascending nubmer
for (int i = 0; i < a.length-1; i++) {
for (int j = 0; j < a.length-i-1; j++) {
if (a[j]>a[j+1]) {
temp = a[j];
a[j]=a[j+1];
a[j+1]=temp;
}
}
}
//to check sorted array with negative & positive values
System.out.print("{");
for(int number:a)
System.out.print(number + ",");
System.out.print("}\n");
//logic for check closest positive and Integer
for (int i = 0; i < a.length; i++) {
if (a[i]<0 && a[i+1]>0) {
temp = a[i+1];
}
}
return temp;
}
public static void main(String[] args) {
int[] array = {10,-5,5,2,7,-4,28,65,95,85,12,45};
int closets =getClosestToZero(array);
System.out.println("The Closest Positive number is : "+closets);
}
}
static void closestToZero(){
int[] arr = {45,-4,-12,-2,7,4};
int max = Integer.MAX_VALUE;
int closest = 0;
for (int i = 0; i < arr.length; i++){
int value = arr[i];
int abs = Math.abs(value);
if (abs < max){
max = abs;
closest = value;
}else if (abs == max){
if (value > closest){
closest = value;
}
}
}
Return a positive integer if two absolute values are the same.
package solution;
import java.util.Scanner;
public class Solution {
public static void trier(int tab[]) {
int tmp = 0;
for(int i = 0; i < (tab.length - 1); i++) {
for(int j = (i+1); j< tab.length; j++) {
if(tab[i] > tab[j]) {
tmp = tab[i];
tab[i] = tab[j];
tab[j] = tmp;
}
}
}
int prochePositif = TableauPositif(tab);
int procheNegatif = TableauNegatif(tab);
System.out.println(distanceDeZero(procheNegatif,prochePositif));
}
public static int TableauNegatif(int tab[]) {
int taille = TailleNegatif(tab);
int tabNegatif[] = new int[taille];
for(int i = 0; i< tabNegatif.length; i++) {
tabNegatif[i] = tab[i];
}
int max = tabNegatif[0];
for(int i = 0; i <tabNegatif.length; i++) {
if(max < tabNegatif[i])
max = tabNegatif[i];
}
return max;
}
public static int TableauPositif(int tab[]) {
int taille = TailleNegatif(tab);
if(tab[taille] ==0)
taille+=1;
int taillepositif = TaillePositif(tab);
int tabPositif[] = new int[taillepositif];
for(int i = 0; i < tabPositif.length; i++) {
tabPositif[i] = tab[i + taille];
}
int min = tabPositif[0];
for(int i = 0; i< tabPositif.length; i++) {
if(min > tabPositif[i])
min = tabPositif[i];
}
return min;
}
public static int TailleNegatif(int tab[]) {
int cpt = 0;
for(int i = 0; i < tab.length; i++) {
if(tab[i] < 0) {
cpt +=1;
}
}
return cpt;
}
public static int TaillePositif(int tab[]) {
int cpt = 0;
for(int i = 0; i < tab.length; i++) {
if(tab[i] > 0) {
cpt +=1;
}
}
return cpt;
}
public static int distanceDeZero(int v1, int v2) {
int absv1 = v1 * (-1);
if(absv1 < v2)
return v1;
else if(absv1 > v2)
return v2;
else
return v2;
}
public static void main(String[] args) {
int t[] = {6,5,8,8,-2,-5,0,-3,-5,9,7,4};
Solution.trier(t);
}
}
To maintain O(n) time complexity and getting the desired results we have to add another variable called 'num' and assign to it 'near' before changing it's value. And finally make necessary checks. The improvements in the code are are:
public class CloseToZero {
public static void main(String[] args) {
int[] data = {2,3,-2};
int curr = 0;
int near = data[0];
int num=near;
// find the element nearest to zero
for ( int i=0; i < data.length; i++ ){
curr = data[i] * data[i];
if ( curr <= (near * near) ) {
num=near;
near = data[i];
}
}
if(near<0 && near*(-1)==num)
near=num;
System.out.println( near );
}
}
We have to find the Closest number to zero.
The given array can have negative values also.
So the easiest approach would append the '0' in the given array and sort it and return the element next to '0'
append the 0
Sort the Array
Return the element next to 0.
`
N = int(input())
arr = list(map(int, input().split()))
arr.append(0)
arr.sort()
zeroIndex = arr.index(0)
print(arr[zeroIndex + 1])
--> If this solution leaves corner cases please let me know also.
`
if you don't wanna use the inbuilt library function use the below code (just an and condition with your existing code)-
public class CloseToZero {
public static void main(String[] args) {
int[] data = {2,3,-2,-1,1};
int curr = 0;
int near = data[0];
// find the element nearest to zero
for ( int i=0; i < data.length; i++ ){
curr = data[i] * data[i];
if ( curr <= (near * near) && !((curr - (near * near) == 0) && data[i] < 0)) {
near = data[i];
}
}
System.out.println( near );
}
}
!((curr - (near * near) == 0) && data[i] < 0) : skip asignment if if near and curr is just opposit in sign and the curr is negative
public static int find(int[] ints) {
if (ints==null) return 0;
int min= ints[0]; //a random value initialisation
for (int k=0;k<ints.length;k++) {
// if a positive value is matched it is prioritized
if (ints[k]==Math.abs(min) || Math.abs(ints[k])<Math.abs(min))
min=ints[k];
}
return min;
}
public int check() {
int target = 0;
int[] myArray = { 40, 20, 100, 30, -1, 70, -10, 500 };
int result = myArray[0];
for (int i = 0; i < myArray.length; i++) {
if (myArray[i] == target) {
result = myArray[i];
return result;
}
if (myArray[i] > 0 && result >= (myArray[i] - target)) {
result = myArray[i];
}
}
return result;
}
I have added a check for the positive number itself.
Please share your views folks!!
public class ClosesttoZero {
static int closZero(int[] ints) {
int result=ints[0];
for(int i=1;i<ints.length;i++) {
if(Math.abs(result)>=Math.abs(ints[i])) {
result=Math.abs(ints[i]);
}
}
return result;
}
public static void main(String[] args) {
// TODO Auto-generated method stub
int[] ints= {1,1,5,8,4,-9,0,6,7,1};
int result=ClosesttoZero.closZero(ints);
System.out.println(result);
}
}
It can be done simply by making all numbers positive using absolute value then sort the Array:
int[] arr = {9, 1, 4, 5, 6, 7, -1, -2};
for (int i = 0; i < arr.length; ++i)
{
arr[i] = Math.abs(arr[i]);
}
Arrays.sort(arr);
System.out.println("Closest value to 0 = " + arr[0]);
import java.math.*;
class Solution {
static double closestToZero(double[] ts) {
if (ts.length == 0)
return 0;
double closestToZero = ts[0];
double absClosest = Math.abs(closestToZero);
for (int i = 0; i < ts.length; i++) {
double absValue = Math.abs(ts[i]);
if (absValue < absClosest || absValue == absClosest && ts[i] > 0) {
closestToZero = ts[i];
absClosest = absValue;
}
}
return closestToZero;
}
}
//My solution priorizing positive numbers contraint
int closestToZero = Integer.MAX_VALUE;//or we
for(int i = 0 ; i < arrayInt.length; i++) {
if (Math.abs(arrayInt[i]) < closestToZero
|| Math.abs(closestToZero) == Math.abs(arrayInt[i]) && arrayInt[i] > 0 ) {
closestToZero = arrayInt[i];
}
}

Categories