I created a program to find the mode. Then made it print the mode in brackets like "1 3 [5] 4 [5]" but when there is no mode in the array list it declares the first value as the mode, like "[1] 3 4 5". I don't want it to show brackets on first integer if there is no mode.
public static int mode(int[] array) {
int mode = array[0];
int maxCount = 0;
for (int i = 0; i < array.length; i++) {
int value = array[i];
int count = 1;
for (int j = 0; j < array.length; j++) {
if (array[j] == value)
count++;
if (count > maxCount) {
mode = value;
maxCount = count;
}
}
}
return mode;
}
Then I print it this way:
int[] array = ...
int mode = mode(array);
boolean first = true;
for (int elt : array) {
// print separator unless it's the first element
if (first) {
first = false;
} else {
System.out.print(' ');
}
if (elt == mode) {
System.out.print(elt);
} else {
System.out.print('[');
System.out.print(elt);
System.out.print(']');
}
}
System.out.println();
Since your function mode() returns by default the initial element in the array as the mode by default, you cannot tell whether the element is the mode or is a case when there is no mode at all. So, you could make a slight change to the function to return 0 when there is no mode instead, then your code would end up like follows:
class TestMode
{
public static void main (String[] args) throws java.lang.Exception
{
int[] array = {1,3,2,4,5};
int mode = mode(array);
for (int e : array) {
if ((mode!=0) && (e==mode)) {
System.out.print ("["+e+"]");
}
else {
System.out.print(e);
}
System.out.print(" ");
}
}
public static int mode(int[] array) {
int mode = array[0];
int maxCount = 0;
for (int i = 0; i < array.length; i++) {
int value = array[i];
int count = 0;
for (int j = 0; j < array.length; j++) {
if (array[j] == value) count++;
if (count > maxCount) {
mode = value;
maxCount = count;
}
}
}
if (maxCount > 1) {
return mode;
}
return 0;
}
}
EDIT: The following is a function that returns the true mode set:
public static Set<Integer> mode2(List<Integer> list) {
int maxFrequency = 0;
boolean modeFound = false;
Set<Integer> modeSet = new HashSet<>();
Collections.sort(list);
for (int i=0; i<list.size(); i++) {
int number = list.get(i);
int count = 1;
for (; (i+count)<list.size() && list.get(i+count)==number; count++) {}
i+=(count-1);
if (maxFrequency!=0 && count!=maxFrequency) {
modeFound = true;
}
if (count > maxFrequency) {
modeSet.clear();
modeSet.add (number);
maxFrequency = count;
}
else if (count == maxFrequency) {
modeSet.add(number);
}
}
if (!modeFound) {
modeSet.clear();
}
return modeSet;
}
You need to be able to return a value that means 'no mode found' instead of just the first value. Here are three options (in decreasing elegance):
If you are using Java 8, then you could return an Optional<Integer>. Then you could explicitly check if it has a value before using it.
You could return an Integer instead of int and then use null to mean 'no value found'.
Use a special value such as 0 or -1. This is what you are doing currently but it has the disadvantage that one of these numbers could well be the true mode of your sample.
boolean bool = true;
int variable = 0;
for (int i = 0; i < myIntArray.length; i++) {
if (myIntArray[i] > 0) {
if (variable == 0) {
variable = myIntArray[i];
} else if (variable != myIntArray[i]) {
bool = false;
break;
}
}
}
if (bool == true) {
System.out.println(" ");
System.out.println("No mode");
} else {
ArrayList<Integer> maximum = new ArrayList<Integer>();
int maxNum = 0;
for (int i = 0; i < myIntArray.length; i++) {
if (myIntArray[i] > maxNum) {
maxNum = myIntArray[i];
maximum = new ArrayList<Integer>();
maximum.add(i);
} else if (myIntArray[i] == maxNum) {
maximum.add(i);
}
}
System.out.println(" ");
System.out.println("The maximum frequency, or number of occurrences, is " + maxNum + " times for the number " + maximum);
System.out.println("The mode is " + maximum);
}
Use this algorithm when all the integers in the list are 0 and above. If not then initialize mode and temp with a number that is impossible to be present in the set.
public static int getMode(List<Integer> list){
int mode,freqMode,temp,tempFreq;
mode=temp=-1;
freqMode=tempFreq=0;
Collections.sort(list);
for(Integer integer:list){
if(mode == -1){
mode = integer;
freqMode = 1;
}else if(mode == integer){
freqMode++;
}else if(temp != integer){
temp = integer;
tempFreq = 1;
}else if(tempFreq >= freqMode){
mode = integer;
freqMode = tempFreq+1;
temp = -1;
tempFreq = 0;
}else {
tempFreq++;
}
}
return mode;
}
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];
}
}
I have instantiated a 2D array of an editable number of rows and a set number of three columns.
It is randomly filled with 0's and 1's using the Random .nextInt(2) method.
After the array is filled, I want to be able to search the array and return the first occurrence of a 0.
How can I do this?
For example, if i had an array that looked something like this:
1 1 0
0 1 0
1 1 1
The first occurence would be at (0,3). I want to search the array horizontally and when it reaches the third column (the end), it will go to the next row.
Note: I originally tested the following section of code with a 2D array that was completely filled with 0's and when I manually inserted 1's in the array and then tried to search for the first occurence of a 0 it worked. However, the code doesn't work when the array is randomly filled..
public String findNextAvailable()
{
for (int i=0; i<seatlist.length; i++)
{
for (int j=0; j<seatlist[i].length; j++)
{
int k=0;
if (seatlist[0][0]==0)
{
nextavailable= seatchart[0][0];
break;
}
else
if(seatlist[k][j]==0)
{
nextavailable= seatchart[k][j];
break;
}
else
{ k++;
if(seatlist[k][j]==0)
{
nextavailable= seatchart[k][j];
break;
}
}
}
}
return nextavailable;
}
Thanks in advance!
for (int i = 0; i < seats.length; i++) {
for (int j = 0; j < seats[i].length; j++) {
if (seats[i][j] == 0) {
return "Next available seat at position: [" + i + "][" + j + "]";
}
}
}
return "No seat available";
Although you might want to create a seat object instead that is easier to work with:
public class Seat {
private int row;
private int column;
public Seat(int row, int column){
this.row = row;
this.column = column;
}
public int getRow() {
return row;
}
public int getColumn() {
return column;
}
}
and replace the returning of a string with:
return new Seat(i,j);
well when you break in the inner loop, you still execute again the outer loop and you wind up replacing what you think is your final result by the next run of the outer loop. rather than use break, just return right there.
You need to return the positions of the first encountered 0, so why are you breaking out of the if statement, the outer loop will still run!
Simply create an integer array:
int[] pos=new array[2];
Change the return type:
public int[] findNextAvailable(){
In each of the if statements change the contents so that it reads:
pos[0]=i;
pos[1]=j;
return pos;
The end result will look something like this:
public int[] findNextAvailable()
{
int[] pos=new array[2];
for (int i=0; i<seatlist.length; i++)
{
for (int j=0; j<seatlist[i].length; j++)
{
if (seatlist[i][j]==0)
{
pos[0]=i;
pos[1]=j;
return pos;
}
}
}
//none found so return minus one.
pos[0]=-1;
pos[1]=-1;
return pos;
}
there are many different types of searches, some faster and some easier to do. Here's a program i made that has methods for all types of them. you will have to modify them a bit so it will search a 2d array but it shouldn't be too hard.
'
package linear_search;
import java.util.Arrays;
import java.util.Scanner;
public class Linear_search {
int[] array = {10,12,42,7,22,1,3,4,5,9};
int ans;
int num;
int min;
int max;
void start(){
arraySort(array);
dump(array);
Scanner scan = new Scanner(System.in);
System.out.println("Enter a value to search:");
num = scan.nextInt();
ans = recursiveBinarySearch(array, 0, array.length-1);
if(ans == -1){
System.out.println("Your value was not found");
} else {
System.out.println("Your value was found at position " + ans);
}
}
void dump(int[] array){
for(int i = 0; i < array.length ; i++){
System.out.print(array[i] + " ");
}
System.out.println();
}
int linearsearch(int[] array){
for(int i = 0; i < array.length; i++){
if(array[i] == num){
return i;
}
}
return -1;
}
int binarysearch(int[] array){
min = 0;
max = array.length -1;
int mid = (min + max) / 2;
while(array[mid] != num){
if(num > array[mid]){
min = mid+1;
mid = (min + max) / 2;
}
if(num < array[mid]){
max = mid-1;
mid = (min + mid) / 2;
}
if(min == max && array[mid] != num){
return -1;
}
}
return mid;
}
int recursiveBinarySearch(int[] array, int min, int max){
int mid = (min + max) / 2;
if(array[mid] == num){
return mid;
}
if(min == max && array[mid] != num){
return -1;
}
if(num > array[mid]){
return recursiveBinarySearch(array, mid+1, max);
}
if(num < array[mid]){
return recursiveBinarySearch(array, min, mid-1);
}
return mid;
}
void arraySort(int[] a){
Arrays.sort(array);
}
public static void main(String[] args) {
Linear_search main = new Linear_search();
main.start();
}
}
'
you will just have to remove the scanner and hard code in "0" for the default value you should search for.