To count unique digits in a given number N in java - java

Given a number N, for example, take 1091, here the count of digits is 4 but the count of unique digits is 3 i.e. 1, 0 & 9 are unique (since 1 is repeated).
I have tried breaking the number into individual digits and adding it to ArrayList and later converting it to an array. Then, iterating through the array and increasing the count of unique digits by 1 every time I got a unique digit in the array, But I have not got the required output. Kindly someone help in finding the unique digits count in a given number in Java.
import java.util.ArrayList;
public class UniqueDigits {
static int uniqueDigitCount(int n) {
ArrayList<Integer> ar = new ArrayList<>();
int temp = n;
int count = 1;
do {
ar.add(temp % 10);
temp /= 10;
}
while (temp > 0);
Integer[] arr = new Integer[ar.size()];
arr = ar.toArray(arr);
if (arr.length > 0) {
for (int i = 0; i < arr.length - 1; i++) {
if (arr[i] != arr[i + 1]) {
count++;
}
}
return count;
} else {
return 0;
}
}
public static void main(String[] args) {
System.out.println(uniqueDigitCount(1091));
}
}

static int uniqueDigitCount(int n) {
HashSet<Integer> hs = new HashSet<Integer>();
int count;
if(n == 0)
{
count = 1;
}
else
{
while(n > 0)
{
hs.add(n % 10);
n /= 10;
}
count = hs.size();
}
return count;
}
A HashSet stores only unique elements. So, when we return the length of the HashSet after adding each digit of the input integer to it, we can obtain the count of unique digits in that input.

This could be done with a set. A set is a collection of unique elements. Putting all characters (digits) into a set will result in the duplicates being discarded. Its size() will then return the distinct elements.
Using streams:
int number = 1091;
long uniques = String.valueOf(number).chars()
.mapToObj(c -> c)
.collect(Collectors.toSet())
.size();
Or leveraging a count on the stream:
String.valueOf(number).chars()
.distinct()
.count();

import java.util.ArrayList;
import java.util.HashSet;
public class UniqueDigits {
static int uniqueDigitCount(int n) {
ArrayList<Integer> ar = new ArrayList<>();
int temp = n;
int count = 1;
do {
ar.add(temp % 10);
temp /= 10;
} while (temp > 0);
Integer[] arr = new Integer[ar.size()];
arr = ar.toArray(arr);
HashSet<Integer> hs = new HashSet<Integer>();
for (int i = 0; i < arr.length - 1; i++) {
hs.add(arr[i]);
}
return hs.size();
}
public static void main(String[] args) {
System.out.println(uniqueDigitCount(1091));
}
}

For a detailed explanation do check my article on gfg (Count of unique digits in a given number N):
import java.util.*;
class UniqueDigits {
// Function that returns the count
// of unique digits of number N
public static void
countUniqueDigits(int N)
{
// Initialize a variable to
// store count of unique digits
int res = 0;
// Initialize cnt array to
// store digit count
int cnt[] = { 0, 0, 0, 0, 0,
0, 0, 0, 0, 0 };
// Iterate through digits of N
while (N > 0) {
// Retrieve the last
// digit of N
int rem = N % 10;
// Increase the count
// of the last digit
cnt[rem]++;
// Remove the last
// digit of N
N = N / 10;
}
// Iterate through the
// cnt array
for (int i = 0;
i < cnt.length; i++) {
// If frequency of
// digit is 1
if (cnt[i] == 1) {
// Increment the count
// of unique digits
res++;
}
}
// Return the count of unique digit
System.out.println(res);
}
public static void main(String[] args)
{
// Given Number N
int N = 2234262;
// Function Call
countUniqueDigits(N);
}
}

Related

Can we solve this Sock Merchant problem in less complexity?

I have solved the hackerrank Sock Merchant problem But I want to reduce the complexity of the code(I am not sure that it is possible or not).
John works at a clothing store. He has a large pile of socks that he must pair by color for sale. Given an array of integers representing the color of each sock, determine how many pairs of socks with matching colors there are.
For example, there are n=7 socks with colors ar= [1,2,1,2,1,3,2]. There is one pair of color 1 and one of color 2. There are three odd socks left, one of each color. The number of pairs is 2.
Function Description
Complete the sockMerchant function in the editor below. It must return an integer representing the number of matching pairs of socks that are available.
sockMerchant has the following parameter(s):
n: the number of socks in the pile
ar: the colors of each sock
Input Format
The first line contains an integer n, the number of socks represented in ar.
The second line contains n space-separated integers describing the colors ar[i] of the socks in the pile.
Constraints
1 <= n <= 100
1 <= ar[i] <= 100 where 0 <= i < n
Output Format
Return the total number of matching pairs of socks that John can sell.
Sample Input
9
10 20 20 10 10 30 50 10 20
Sample Output
3
My solutions :
package com.hackerrank.test;
public class Solution {
public static void main(String[] args) {
//Initialize array
int[] arr = new int[]{10, 20, 20, 10, 10, 30, 50, 10, 20};
//Array fr will store frequencies of element
System.out.println("---------------------------------------");
System.out.println(" sockMerchant output " + sockMerchant(9, arr));
System.out.println("---------------------------------------");
}
static int sockMerchant(int n, int[] ar) {
int pairs = 0;
int frequencyArray[] = new int[ar.length];
int frequencyTemp = -1;
for (int i = 0; i < ar.length; i++) {
int count = 1;
for (int j = i + 1; j < ar.length; j++) {
if (ar[i] == ar[j]) {
count++;
frequencyArray[j] = frequencyTemp;
}
}
if (frequencyArray[i] != frequencyTemp) {
frequencyArray[i] = count;
}
}
for (int i = 0; i < frequencyArray.length; i++) {
if (frequencyArray[i] != frequencyTemp) {
int divide = frequencyArray[i] / 2;
pairs += divide;
}
}
return pairs;
}
}
And the output is :
---------------------------------------
sockMerchant frequency 3
---------------------------------------
You can solve this in a single pass (O(n)) using a HashSet, which has O(1) put and lookup time. Each element is already in the set, in which case it gets removed and the pair counter is incremented, or it's not, in which case you add it:
int[] arr = new int[]{10, 20, 20, 10, 10, 30, 50, 10, 20};
HashSet<Integer> unmatched = new HashSet<>();
int pairs = 0;
for(int i = 0; i < arr.length; i++) {
if(!unmatched.add(arr[i])) {
unmatched.remove(arr[i]);
pairs++;
}
}
This works for java 8!!
static int sockMerchant(int n, int[] ar) {
Set<Integer> list = new HashSet<Integer>();
int count = 0;
for(int i= 0; i < n; i++){
if(list.contains(ar[i])){
count++;
list.remove(ar[i]);
}
else{
list.add(ar[i]);
}
}
return count;
}
It can also be solved using a dictionary as follows in Swift:
func sockMerchant(n: Int, ar: [Int]) -> Int {
var dictionary: [Int: Int] = [:]
var totalNumberOfPairs: Int = 0
// Store all array elements in a dictionary
// with element as key and occurrence as value
ar.forEach{
dictionary[$0] = (dictionary[$0] ?? 0) + 1
}
// Iterate over the dictionary while checking for occurrence greater or equal 2.
// If found add the integer division of the occurrence to the current total number of pairs
dictionary.forEach { (key, value) in
if value >= 2 {
totalNumberOfPairs = totalNumberOfPairs + (value / 2)
}
}
return totalNumberOfPairs
}
Here my solution with JAVA for Sock Merchant test on HackerRank
import java.io.*;
import java.util.*;
public class sockMerchant {
public static void main(String[] args) {
Scanner en = new Scanner(System.in);
int n=en.nextInt();
int[] hash = new int[300];
for(int i=0; i<n; i++){
hash[en.nextInt()]++;
}
long res=0;
for(int f: hash){
res+=f/2;
}
System.out.println(res);
}
}
Py3 solution for the problem using dictionaries
def sockMerchant(n, ar):
pair = 0
d = {}
for i in ar:
if i in d:
d[i] += 1
if i not in d:
d[i] = 1
print(d)
for x in d:
u = d[x]//2
pair += u
return pair
Code for python 3
n = 9
ar = [10, 20, 20, 10, 10, 30, 50, 10, 20]
def sockMerchant(n, ar):
totalpair = 0
test= list(set(ar))
for i in test:
pair = 0
for j in ar:
if i==j:
pair+=1
if pair>=2:
totalpair=totalpair+int(pair/2)
return totalpair
print(sockMerchant(n,ar))
We can use a Hash Table, for it. As Hash Table's Complexity is O(1)
Look at below code snippet, i created a dictionary in python i.e. Hash Table having key and value. In dictionary, there only exists a unique Key for each value. So, at start dictionary will be empty. We will loop over the provided list and check values in dictionary keys. If that value is not in dictionary key, it means it is unique, add it to the dictionary. if we find value in dictionary key, simply increment pairs counter and remove that key value pair from hash table i.e. dictionary.
def sockMerchant(n, ar):
hash_map = dict()
pairs = 0
for x in range(len(ar)):
if ar[x] in hash_map.keys():
del hash_map[ar[x]]
pairs += 1
else:
hash_map.setdefault(ar[x])
return pairs
This is my simple code for beginners to understand using c++ which prints the count of numbers of pair in the user-defined vector:
#include <bits/stdc++.h>
using namespace std;
vector<string> split_string(string);
// Complete the sockMerchant function below.
int sockMerchant(int n, vector<int> ar) {
int count=0;
vector<int> x;
for(int i=0;i<n;i++){
if(ar[i]!=0)
{
for(int j=i+1;j<n;j++)
{
if(ar[i]==ar[j]){
count++;
ar[j]=0;
break;
}
}}
}
return count;
}
int main()
{
int a,b;
vector<int> v;
cin>>a;
for(int i=0;i<a;i++){
cin>>b;
v.push_back(b);
}
cout<<sockMerchant(a,v);
}
function sockMerchant(n, ar) {
//Need to initiate a count variable to count pairs and return the value
let count = 0
//sort the given array
ar = ar.sort()
//loop through the sorted array
for (let i=0; i < n-1; i++) {
//if the current item equals to the next item
if(ar[i] === ar[i+1]){
//then that's a pair, increment our count variable
count++
//also increment i to skip the next item
i+=1
}
}
//return the count value
return count
}
sockMerchant(9, [10, 20, 20, 10, 10, 30, 50, 10, 20])
For Javascript
function sockMerchant(n, ar) {
// Create an initial variable to hold the pairs
let pairs = 0;
// create an object to temporarily assign pairs
const temp = {};
// loop through the provided array
for (let n of ar) {
// check if current value already exist in your temp object
if (temp[n] in temp) {
// if current value already exist in temp
// delete the value and increase pairs
delete temp[n];
pairs += 1;
} else {
// else add current value to the object
temp[n] = n;
}
}
// return pairs
return pairs;
}
package com.java.example.sock;
import java.io.IOException;
/**
*
* #author Vaquar Khan
*
*/
public class Solution1 {
// Complete the sockMerchant function below.
/*
* John works at a clothing store. He has a large pile of socks that he must pair by color for sale. Given an array of integers representing the color of each sock, determine how many pairs
* of socks with matching colors there are.
* For example, there are socks with colors . There is one pair of color and one of color . There are three odd socks left, one of each color. The number of pairs is .
*/
static int sockMerchant(int n, int[] ar) {
int counter = 0;
int count = 0;
//
for (int i = 0; i < ar.length; i++) {
count = 1;
//
for (int j = i + 1; j < ar.length; j++) {
if (ar[i] == ar[j]) {
count++;
}
}
if (count % 2 == 0) {
counter++;
}
}
return counter;
}
public static void main(String[] args) throws IOException {
int array[] = { 10, 20, 20 ,10 ,10, 30, 50, 10 ,20};
System.out.println(sockMerchant(9, array));
}
}
Refer below one using HashMap and having complexity O(1)
static int sockMerchant(int n, int[] ar) {
int pairs=0;
Map<Integer, Integer> map = new HashMap<>();
for(int i=0;i<n;i++){
if(map.containsKey(ar[i])){
int count=map.get(ar[i]);
map.put(ar[i],++count);
}
else{
map.put(ar[i],1);
}
}
for(int i : map.values()){
pairs=pairs+(i/2);
}
return pairs;
}
static int sockMerchant(int n, int[] ar) {
int pairs = 0;
for (int i = 0; i < ar.length; i++) {
int counter = 0;
for (int j = 0; j < ar.length; j++) {
if (j < i && ar[j] == ar[i]) break;
if(ar[j]==ar[i]) counter++;
}
pairs+=counter/2;
}
return pairs;
}
def sockMerchant(n, ar):
socks = dict()
pairs = 0
for i in ar:
if i in socks:
socks[i] = socks[i]+1
if i not in socks:
socks[i] = 1
if socks[i]%2 == 0:
pairs += 1
return pairs
This problem can be done easily with a hashset. We can take advantage of the HashSet's ability to not store duplicate elements. Here is the code below.
Set<Integer> set = new HashSet<>();
int pairCount = 0;
for(int i = 0; i < arr.length; i++) {
if(set.add(a[i])
set.add(a[i])
else {
pairCount++;
set.remove(a[i]);
}
}
return pairCount;
/*
* Complete the 'sockMerchant' function below.
*
* The function is expected to return an INTEGER.
* The function accepts following parameters:
* 1. INTEGER n
* 2. INTEGER_ARRAY ar
*/
function sockMerchant(n, ar) {
// Write your code here
let count = [];
for (var i = 0; i < ar.length; i++) {
if (count.hasOwnProperty(ar[i])) {
count[ar[i]]++;
}
else {
count[ar[i]] = 1;
}
}
let number = 0;
for (const key in count) {
number += parseInt(count[key] / 2);
}
return number;
}
My answer in C
int sockMerchant(int n, int ar_count, int* ar) {
int matchcounter =0;// each number repeating count
int paircounter=0;//total pair
int size=0;int i,j,k;
bool num_av=false;//number available or not in new array
int numberarray[n];//creating new (same length) array of length n
for(i=0;i<n;i++){
num_av=false;
for(k=0;k<=size;k++){
if(numberarray[k] == ar[i]){
num_av=true;
break;
}
}
if(!num_av){
size+=1;
numberarray[size-1]=ar[i];
for(j=0;j<n;j++){
if(ar[i]==ar[j]){
matchcounter++;
}
}
paircounter += matchcounter/2;
matchcounter=0;
}
}
return paircounter;
}
I wanted to solve this using Array. Here is my solution for Sock Merchant problem on HackerRank (Java 8):
....
import org.apache.commons.lang3.ArrayUtils;
import java.util.Arrays;
class Result {
public static int sockMerchant(int n, List<Integer> ar) {
int[] arr = ar.stream().mapToInt(i->i).toArray();
int counter = 0;
for(int i = 0; i<n; i++) {
if(arr[i]>0) {
int t = arr[i];
arr[i] = -1;
int j = ArrayUtils.indexOf(arr, t);
if(j == -1) {
continue;
} else {
arr[j] = -1;
counter += 1;
}
} else {
continue;
}
}
return counter;
}
}
This has a O(n) time complexity.
Code for Javascript
const set = new Set()
let count = 0;
for(let i = 0; i < i; i++) {
if (set.has(ar[i])) {
count++;
set.delete(ar[i])
} else {
set.add(ar[i])
}
}
You can count the number of times a number appears in the list and divide them by 2
def sockMerchant(n, ar):
unq = set(ar)
count = 0
for i in unq:
count_vals = ar.count(i)
if count_vals>1:
count = count + int(count_vals/2)
return count
The more easiest way I preferred. Answer in Kotlin
var counter = 0
for (i in 0 until n) {
if (arr[i] != 0) {
loop# for (j in i + 1 until n) {
if (arr[i] == arr[j]) {
counter++
arr[j] = 0
break#loop
}
}
}
}
Commenting for better programming
it can also be solved using the built in Set data type as below (my try) -
function sockMerchant(n, ar) {
// Write your code here
let numberSet = [...new Set(ar)];
let pairs = 0;
for(let i=0;i<numberSet.length;i++){
let count = 0;
ar.filter(x => {
if(x == numberSet[i])
count++;
});
pairs+= count / 2 >= 1 ? Math.trunc(count / 2) : 0;
}
return pairs;
}
Using Python 3:
def sockMerchant(n, ar):
flag = 0
for i in range(n):
if ar[i:].count(ar[i])%2==0:
flag+=1
return flag
Think how you would do it in real life. If someone handed you these socks one-by-one, you'd like think, "Do I have one of these already?" If not, you'd set it down and move on to check on the next sock. When you find one you've already set down, you'd move the pair to the side and count that as another found pair.
Programmatically you may take advantage of a HashSet given it's quick access (constant) and that it only allows for one entry per unique key. Therefore, you can attempt add to the set. Failure to do so means it already exists, count and remove the pair, and continue.
Time-complexity: O(n) [n = number of socks]
Space-complexity: O(m) [m = number of UNIQUE sock types]
Java 8:
public static int sockMerchant(int n, List<Integer> ar)
{
Set<Integer> uniqueSockFound = new HashSet<Integer>();
int countedPairs = 0;
//Iterate through each sock checking if a match has been found already or not
for(Integer sock: ar)
{
//If adding the sock to the set is a success, it doesn't exist yet
//Otherwise, a pair exists, so remove the item and increment the count of pairs
if(!uniqueSockFound.add(sock))
{
countedPairs++;
uniqueSockFound.remove(sock);
}
}
//Return count of pairs
return countedPairs;
}
Here is my solution and it worked for the given set of inputs.
import java.util.*;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int size = sc.nextInt();
int[] arr = new int[size];
for (int i = 0 ; i < size ; i++) {
arr[i] = sc.nextInt();
}
int flag = 0;
for (int j = 0; j < size; j++) {
int count = 0;
for(int i = j + 1; i < size ; i++) {
if (arr[j] == arr[i]) {
count++;
}
}
flag += count / 2;
}
System.out.println(flag);
}
}
I solve it with golang
func sockMerchant(n int32, ar []int32) int32 {
// Write your code here
var indexPairs []int;
var count int32;
var operation bool;
for i := 0; i< len(ar)-1; i++{
for j := i+1; j< len(ar); j++{
//check indexPairs
operation = true;
for k := 0; k< len(indexPairs); k++{
if indexPairs[k] == i || indexPairs[k]==j{
operation = false;
}
}
if operation {
if(ar[i]==ar[j]){
count ++;
indexPairs = append(indexPairs, i, j)
}
}
}
}
return count;
}```
using PYTHON language
from itertools import groupby
def sockmerchant(n,ar):
c=0
a=[]
ar.sort()
for k,g in groupby(ar): # in this same elements group into one list
a.append(len(list(g)))
for i in a:
c=c+(i//2)
return c
n=int(input())
ar=list(map(int,input().split(' ')))
print(sockMerchant(n,ar))
function sockMerchant(n, ar){
let res = 0;
let arr= {};
for (let element of ar){
arr[element] = arr[element]+1 || 1
if(arr[element]%2 == 0){
res++;
}
}
return res;
}
sockMerchant(4,[10,10,20,20]);
public static int sockMerchant(int n, List<Integer> ar) {
int pair = 0;
List<Integer> matchedIndices = new ArrayList<>();
for (int i = 0; i < n; i++) {
if (matchedIndices.contains(i)) {
continue;
}
for (int j = 0; j < n; j++) {
if (j == i || matchedIndices.contains(j)) {
continue;
}
if (ar.get(i) == ar.get(j)) {
pair++;
matchedIndices.add(i);
matchedIndices.add(j);
break;
}
}
}
return pair;
}
I will give an example of solving this problem in C++ using unordered_map. It's overkill, to be honest, and it's done with unordered_set as well (removing the element as a replacement for a boolean in the map). But this more clearly shows the coding path to first do everything right, and only after that take an optimization step and convert to unordered_set.
using namespace std;
/*
* Complete the 'sockMerchant' function below.
*
* The function is expected to return an INTEGER.
* The function accepts following parameters:
* 1. INTEGER n
* 2. INTEGER_ARRAY ar
*/
int sockMerchant(int n, vector<int> ar) {
if (n<1 && n>100 ) return 0;
unordered_map<int, bool> scExtract;
int result=0;
// false --first sock finded
// true --second sock funded
for (auto sCol:ar) {
if (sCol<1 && sCol>100 ) return 0;
if (scExtract.find(sCol) != scExtract.end()) {
if ( scExtract[sCol]) {
scExtract[sCol]=false;
} else {
scExtract[sCol]=true;
result++;
}
} else {
scExtract.insert(pair<int, bool>(sCol, false));
}
}
return result;
}

prime factorization decryption

I have a program that is supposed to decrypt a number to its primes. The primes also have an order: for instance, 2 is the 1st prime number, 3 is the second 5 is the third and so on. The indexes are 1 is for a, two is for b, three is for c and so on. I don't know how to compare the two array lists in order to assign an index to each prime so I can decode a word which is encrypted in the number 72216017. The number 72216017 has the primes 17,19,47,67,71. If 2,3,5,7,11... are a,b,c,d,e... these five prime numbers make up the word ghost, I just don't know how to assign and sort these numbers by their index.
package name;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
public class PrimeFactorsEffective {
private static int z;
private int w = z;
public static List<Integer> primeFactors(int numbers) {
int n = numbers;
List<Integer> factors = new ArrayList<Integer>();
for (int i = 2; i <= n / i; i++) {
while (n % i == 0) {
factors.add(i);
n /= i;
}
if (n > 1) {
factors.add(n);
System.out.println(factors);
z = Collections.max(factors);
}
}
return factors;
}
public static void main(String[] args) {
System.out.println("Primefactors of 72216017");
for (Integer integer : primeFactors(72216017)) {
System.out.println(integer);
}
List<Integer> factors1 = new ArrayList<Integer>();
List<String> index1 = new ArrayList<String>();
int i;
int element = 0;
int num = 0;
int maxCheck = z; // maxCheck limit till which you want to find prime numbers
boolean isPrime = true;
String primeNumbersFound = "";
//Start loop 1 to maxCheck
for (i = 1; i <= maxCheck; i++) {
isPrime = CheckPrime(i);
if (isPrime) {
primeNumbersFound = primeNumbersFound + i + " ";
factors1.add(i);
factors1.get(num);
}
}
System.out.println("Prime numbers from 1 to " + maxCheck + " are:");
System.out.println(factors1);
}
public static boolean CheckPrime(int numberToCheck) {
int remainder;
for (int i = 2; i <= numberToCheck / 2; i++) {
remainder = numberToCheck % i;
if (remainder == 0) {
return false;
}
}
return true;
}
}
You can store the primes in a List (primes in this list will be in increasing order). Now you can use Collections.BinarySearch to get the index of the prime for which you wan to find the corresponding alphabet. Once you got the index (index here according to you starts from 1, so a's index is 1, b's index is 2, c's index is 3 and so on) you can do simply something like char currentCharacter = (char) ('a' + primeIndex - 1) and the variable currentCharacter will store the alphabet corresponding to primeIndex.
Some other minor things that I'd like to suggest:
Which checking whether a number is prime or not, you can simply check upto square-root of numberToCheck. So you can replace your loop for (int i = 2; i <= numberToCheck / 2; i++) to for (int i = 2; i*i <= numberToCheck; i++). Note that It is not a good idea to calculate square-root using Math.sqrt, instead you can have a condition like i*i <= numberToCheck.
Please refrain from naming your packages that seem to be random.
As of Java SE 7 explicit type-arguments while initializing the list are not required. You can replace List<Integer> factors1 = new ArrayList<Integer>() with List<Integer> factors1 = new ArrayList<>(). Please read this for more information.
Your factor method don't really look good to me, it don't give correct results. Please see the following method that gives correct result:
{{
public static List<Integer> primeFactors(int numbers) {
int n = numbers;
List<Integer> factors = new ArrayList<>();
for (int i = 2; n>1; i++) {
while (n % i == 0) {
factors.add(i);
n /= i;
}
}
z = Collections.max(factors);
return factors;
}

Returning the index of the n-th highest value of an unsorted list

I have written the following code and am now trying to figure out the best way to achieve what is explained in the four comments:
Integer[] expectedValues = new Integer[4];
for (int i = 0; i <= 3; i++) {
expectedValues[i] = getExpectedValue(i);
}
int choice = randomNumGenerator.nextInt(100) + 1;
if (choice <= intelligence) {
// return index of highest value in expectedValues
} else if (choice <= intelligence * 2) {
// return index of 2nd highest value in expectedValues
} else if (choice <= intelligence * 3) {
// return index of 3rd highest value in expectedValues
} else {
// return index of lowest value in expectedValues
}
What would be an elegant way o doing so? I do not need to keep expected values as an array - I am happy to use any data structure.
You could create a new array containing the indices and sort on the values - in semi-pseudo code it could look like this (to be adapted):
int[][] valueAndIndex = new int[n][2];
//fill array:
valueAndIndex[i][0] = i;
valueAndIndex[i][1] = expectedValues[i];
//sort on values in descending order
Arrays.sort(valueAndIndex, (a, b) -> Integer.compare(b[1], a[1]));
//find n-th index
int n = 3; //3rd largest number
int index = valueAndIndex[n - 1][0];
If you want to work with simple arrays, maybe this might be a solution:
public static void main(String[] args) {
int[] arr = new int[] { 1, 4, 2, 3 };
int[] sorted = sortedCopy(arr);
int choice = randomNumGenerator.nextInt(100) + 1;
if (choice <= intelligence) {
System.out.println(findIndex(arr, sorted[3])); // 1
} else if (choice <= intelligence * 2) {
System.out.println(findIndex(arr, sorted[2])); // 3
} else if (choice <= intelligence * 3) {
System.out.println(findIndex(arr, sorted[1])); // 2
} else {
System.out.println(findIndex(arr, sorted[0])); // 0
}
}
static int[] sortedCopy(int[] arr) {
int[] copy = new int[arr.length];
System.arraycopy(arr, 0, copy, 0, arr.length);
Arrays.sort(copy);
return copy;
}
static int findIndex(int[] arr, int val) {
int index = -1;
for (int i = 0; i < arr.length; ++i) {
if (arr[i] == val) {
index = i;
break;
}
}
return index;
}
You can "wipe out" the highest value n-1 times. After this the highest value is the n-th highest value of the original array:
public static void main(String[] args) {
int[] numbers = new int[]{5, 9, 1, 4};
int n = 2; // n-th index
for (int i = 0; i < n - 1; ++i) {
int maxIndex = findMaxIndex(numbers);
numbers[maxIndex] = Integer.MIN_VALUE;
}
int maxIndex = findMaxIndex(numbers);
System.out.println(maxIndex + " -> " + numbers[maxIndex]);
}
public static int findMaxIndex(int[] numbers) {
int maxIndex = 0;
for (int j = 1; j < numbers.length; ++j) {
if (numbers[j] > numbers[maxIndex]) {
maxIndex = j;
}
}
return maxIndex;
}
The complexity is O(n * numbers.length).

calculating consecutive 1's in a Binary number

import java.util.Scanner;
import java.util.Arrays;
class Solve
{
public static void main(String args[])
{
Scanner in = new Scanner(System.in);
int i=0,count=0;
int[] arr = new int[10];
int n =in.nextInt();
while(n!=0)
{
arr[i]=n%2;
i++;
n=n/2;
}
System.out.println(Arrays.toString(arr));
}
}
}
I just want to calculate number of consecutive 1's. ? like 1110011001 will give me answer 5.. How can i do that??
System.out.println(Integer.toBinaryString(n).replaceAll("(0|(?<!1)1(?!1))", "").length());
The regex means: replace all 0's and any 1 not preceded or followed by another 1
You can handle this as a String [Edited to sum all consecutive 1's]:
String binary = in.nextLine();
String[] arrayBin = binary.split("0+"); // an array of strings without 0's
int result=0;
for (int i=0; i < arrayBin.length; i++){
if (arrayBin[i].length()<2){
result+=0;
}
else {
result+=arrayBin[i].length();
}
}
System.out.println("Total consecutive = "+result);
We can identify two consecutive binary ones in the least significant positions like this:
(value & 0b11) == 0b11
We can move the bits in value to the right like so:
value >>>= 1;
It's important to use tripple >>> over double >> because we don't care about the sign bit.
Then all we have to do is keep track of the number of consecutive 1s:
int count(int value) {
int count = 1;
int total = 0;
while (value != 0) {
if ((value & 0b11) == 0b11) {
count++;
} else {
if (count > 1) {
total += count;
}
count = 1;
}
value >>>= 1;
}
return total;
}
Test cases:
assertEquals(0, count(0b0));
assertEquals(0, count(0b1));
assertEquals(0, count(0b10));
assertEquals(2, count(0b11));
assertEquals(5, count(0b1110011));
assertEquals(5, count(0b1100111));
assertEquals(6, count(0b1110111));
assertEquals(7, count(0b1111111));
assertEquals(32, count(-1));
If you only want the length of the maximum, I have a similar answer: https://stackoverflow.com/a/42609478/360211
You can make use of Brian Kernighan’s Algorithm for counting the highest consecutive number of 1's.
A java pseudocode would be something like this
// Initialize result
int count = 0;
// Count the number of iterations to
// reach n = 0.
while (n!=0)
{
// This operation reduces length
// of every sequence of 1s by one.
n = (n & (n << 1));
count++;
}
public class Solution {
public int findMaxConsecutiveOnes(int[] nums) {
if(nums == null || nums.length == 0){
return 0;
}
int counter = 0, max = Integer.MIN_VALUE;
for(int i = 0; i < nums.length; i++){
if(nums[i] == 1){
counter += nums[i];
} else{
counter = nums[i];
}
max = Math.max(counter, max);
}
return max;
}
}
To this problem one trick which we can use here with help of some Java operators.
& operator and left shift (<<) in java.
Code snippet will be like :
public getConsecutiveCount(int inputNumber)
{
int count = 0 ;
while(inputNumber != 0)
{
inputNumber = inputNumber & (inputNumber << 1);
count++;
}
}
Explanation :
This function is taking input (ex : we want to check how many
consecutive 1's integer 6 have in its binary representation)
so out input number will be like :
inputNumber = ((110) & ((110)<<1)) {This left shift will result in 100 so final op :
110 & 100 which 100 , every time '0' is added to
our result and we iterate until whole number will
be zero and value of our count variable will be
our expected outcome }
To find Maximum consecutive 1's in binary(like 101)
int n = Convert.ToInt32(Console.ReadLine());
string[] base2=Convert.ToString(n,2).Split('0');
int count=0;
foreach(string s in base2)
count=s.Length>count?s.Length:count;
Console.WriteLine(count);
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int n = in.nextInt();
String bs = Integer.toBinaryString(n);// bs=Binary String
char[] characters = bs.toCharArray();
int max = 1;
int temp = 1;
for (int i = 0; i < characters.length - 1; i++) {
if (characters[i] == characters[i + 1] & characters[i] == '1' & characters[i + 1] == '1') {
temp++;
if (temp > max) {
max = temp;
}
} else {
temp = 1;
}
}
System.out.println(max);
}
/* Given a decimal number print maximum number of consecutive 1's after binary conversion */
import java.io.*;
import java.util.*;
public class Solution {
public void countBinaryOne(int num){
int var =0, countOne= 0, maxCt=0;
while(num>0){
var= num%2;
if(var==1){
countOne=countOne+1;
}else{
if(maxCt<countOne){
maxCt= countOne;
countOne=0;
}else{
countOne=0;
}
}
num=num/2;
}
System.out.println(Math.max(countOne,maxCt));
}
public static void main(String[] args) {
Scanner in= new Scanner(System.in);
int n= in.nextInt();
Solution sol= new Solution();
sol.countBinaryOne(n);
}
}
public static void digitBinaryCountIfOne(int n){
int reminder=0, sum=0, total = 0;
while(n>0)
{
reminder = n%2;
n/=2;
if(reminder==1){
sum++;
if(sum>=total)
total=sum;
}else{
sum=0;
}
}
System.out.println(total);
}

Sorting an array of integers in time complexity of o(n) or o(1)

What is the best algorithm that could sort an array of integers from 1 to 4 (very simple), in a time complexity of o(n) or less?
Use Radix Sort, which is O(n)
public void radixsort(int[] input) {
final int RADIX = 10;
// declare and initialize bucket[]
List<Integer>[] bucket = new ArrayList[RADIX];
for (int i = 0; i < bucket.length; i++) {
bucket[i] = new ArrayList<Integer>();
}
// sort
boolean maxLength = false;
int tmp = -1, placement = 1;
while (!maxLength) {
maxLength = true;
// split input between lists
for (Integer i : input) {
tmp = i / placement;
bucket[tmp % RADIX].add(i);
if (maxLength && tmp > 0) {
maxLength = false;
}
}
// empty lists into input array
int a = 0;
for (int b = 0; b < RADIX; b++) {
for (Integer i : bucket[b]) {
input[a++] = i;
}
bucket[b].clear();
}
// move to next digit
placement *= RADIX;
}
}
code Ref

Categories

Resources