how to get String array containing distinct characters? - java

i have a String "iye" and i want make it distinct and also i have a array ["hi", "bye", "bebe"] and i want to make each element of the array and get the distinct characters only so my array would be like this ["hi", "bye", "be"] an then at last i want to take each element from that distinct array and count how many characters of distinctArray[i] are present in the distinct String "iye" and i will store that count for each element of distinct array in same order respectively to the elements of distinct array for e.g
sample input = "iyee" and ["hi", "bye", "bebe"]
sample ouput = [1, 2, 1]
below is my solution not working for larger inputs
static int[] mathProfessor(String B,String[] a){
List<String> distinct = new ArrayList<String>();
int[] arr = new int[a.length];
// store each value of names array as distinct value
for (int i = 0; i < a.length; i++) {
StringBuilder str = new StringBuilder();
a[i].chars().distinct().forEach(c -> str.append((char) c));
distinct.add(str.toString());
}
// System.out.println("distinct list: " + distinct.toString());
// store the count
int count = 0;
for (int i = 0; i < distinct.size(); i++) {
String s = distinct.get(i);
for (int j = 0; j < B.length(); j++) {
if (s.contains(Character.toString(B.charAt(j))))
count++;
}
arr[i] = count;
count = 0;
}
return arr;
}

static int[] mathProfessor(String b, String[] a) {
b = dist(b);
int count = 0;
String[] arr = new String[a.length];
int[] countArr = new int[a.length];
for (int i = 0; i < a.length; i++) {
arr[i] = dist(a[i]);
}
for (int i = 0; i < arr.length; i++) {
for (int j = 0; j < b.length(); j++) {
if (arr[i].contains(Character.toString(b.charAt(j))))
count++;
}
countArr[i] = count;
count = 0;
}
//System.out.println(Arrays.toString(countArr));
return countArr;
}
public static String dist(String s) {
StringBuilder sb = new StringBuilder();
Set<Character> set = new HashSet<Character>();
for (int i = 0; i < s.length(); i++) {
if (set.add(s.charAt(i)) == true)
sb.append(s.charAt(i));
}
return sb.toString();
}

Using Java 8+ Streams:
static int[] mathProfessor(String b, String[] a) {
var distinctB = dist(b);
System.out.println(distinctB);
var result = new int[a.length];
for(int i=0, j=a.length; i < j; i++) {
result[i] = (int) Arrays.stream(dist(a[i]).split("")).filter(distinctB::contains).count();
}
return result;
}
public static String dist(String s) {
Set<String> set = new HashSet<>();
set.addAll(Arrays.asList(s.split("")));
return String.join("", set);
}

Related

How do I convert a String into a 2D array

I have to define a method called getDistance. That takes the following string:
0,900,1500<>900,0,1250<>1500,1250,0 and returns a 2d array with the all the distances. The distances are separated by "<>" symbol and they are separated into each column by ",".
I know I need to use String.split method. I know splitting by the commmas will give me the columns and splitting it by the "<>" will give me the rows.
public static int[][] getDistance(String array) {
String[]row= array.split(",");
String[][] distance;
int[][] ctyCoord = new int[3][3];
for (int k = 0; k < row.length; k++) {
distance[k][]=row[k].split("<>");
ctyCoord[k][j] = Integer.parseInt(str[j]);
}
return ctyCoord;
This is a working dynamic solution:
public static int[][] getDistance(String array) {
String[] rows = array.split("<>");
int[][] _2d = null;
// let us take the column size now, because we already got the row size
if (rows.length > 0) {
String[] cols = rows[0].split(",");
_2d = new int[rows.length][cols.length];
}
for (int i = 0; i < rows.length; i++) {
String[] cols = rows[i].split(",");
for (int j = 0; j < cols.length; j++) {
_2d[i][j] = Integer.parseInt(cols[j]);
}
}
return _2d;
}
Let's test it:
public static void main(String[] args) {
String given = "0,900,1500<>900,0,1250<>1500,1250,0";
int[][] ok = getDistance(given);
for (int i = 0; i < ok.length; i++) {
for (int j = 0; j < ok[0].length; j++) {
int k = ok[i][j];
System.out.print(k + " ");
}
System.out.println();
}
}
I think you should first split along the rows and then the colums. I would also scale the outer array with the number of distances.
public static int[][] getDistance(String array) {
String[] rows = array.split("<>");
int[][] out = new int[rows.length][3];
for (int i = 0; i < rows.length, i++) {
String values = rows[i].split(",");
for (int j = 0; j < 3, j++) {
out[i][j] = Integer.valueOf(values[j]);
}
}
return out;

Algorithm for combinations of integer in an array

I am having difficulties for writing an algorithm that will create an array of arrays, from a single array of integers.
Say, I have an
int[] intArray = new int[] {1,2,3,4,5};
What I need from it is an array of an arrays that will look like this:
int[][] array = new int[][]{
{-1,2,3,4,5},
{1,-2,3,4,5},
{1,2,-3,4,5},
{1,2,3,-4,5},
{1,2,3,4,-5};
Thank you in advance!!
EDIT:
The following code works for the case if I want to have only one negative value. How about if I would like to have 2,3,4... negative values? Is there a way to make it more dynamic? For example, from {1,2,3,4,5}; to get: {-1,-2,3,4,5}, {-1,2,-3,4,5}, {-1,2,3,-4,5}, {-1,2,3,4,-5}, {1,-‌​2,-3,4,5},{1,-2,3,-4‌​,5}, {1,-2,3,4,-5}...‌​. or for 3 negative values: {-1,-2,-3,4,5}, {-1,-2,3,-4,5}, {-1,-2,3,4,-5}, {1,-2,-3,-4,5},‌ ​{1,-2,-3,4,-5}, {1,2,‌​-3,-4,-5}...etc I hope you get my point! Thanks again guys!!
You could try this:
int l = intArray.length;
int[][] newArray = new int[l][l];
for (int i = 0; i < l; i++) {
for (int j = 0; j < l; j++) {
newArray[i][j] = j == i ? intArray[j] * -1 : intArray[j];
}
}
newArray will have the values you are expecting.
how about
public class x
{
public static int[][] convert(int in[])
{
int s = in.length;
int out[][] = new int[s][s];
for (int i = 0; i < s; ++i) { // row loop
for (int j = 0; j < s; ++j) {
if (i == j)
out[i][j] = -in[j];
else
out[i][j] = in[i];
}
}
return out;
}
public static void print(int in[][])
{
for (int i = 0; i < in.length; ++i) {
String sep = "";
for (int j = 0; j < in[i].length; ++j) {
System.out.print(sep + in[i][j]);
sep = ", ";
}
System.out.println("");
}
}
public static void main(String argv[])
{
int in[] = { 1, 2, 3, 4, 5 };
int out[][];
out = convert(in);
print(out);
}
}
int[] intArray = new int[] {1,2,3,4,5};
int algoIntArray[][] = new int[intArray.length][intArray.length];
for(int i = 0; i < intArray.length; i++){
for (int j = 0; j < algoIntArray[i].length; j++){
if (i == j){
algoIntArray[i][j] = -intArray[j];
} else {
algoIntArray[i][j] = intArray[j];
}
}
}
This code will work for you!

Compressing array values into another array

I came across this problem called compress. The objective is to take an array, remove any repeated values and return a new array.
I know this would be very easy with ArrayLists, but I want to do it without them.
So far, I've just written a loop to determine the number of unique values so I can construct a new array of the appropriate length. How can I then get the unique values into the new array?
public static int[] compress(int[] array){
int length = 0;
boolean contains = false;
for (int i = 0; i < array.length; i++){
contains = false;
for (int j = 0; j < i; j++){
if (a[i] == a[j]){
contains = true;
j = i;
} else {
contains = false;
}
}
if (!contains){
length++;
}
}
int[] uniqueArray = new int[length];
}
Not Tested but I think this should do the trick.
public static int[] copyArray(int [] num){
int x = 0;
int numDuplicate = 0;
int[] copy = new int[num.length]; // we use this to copy the non duplicates
HashMap<Integer, Integer> count = new HashMap<>(); //hashmap to check duplicates
for(int i = 0; i < num.length; i++){
if(count.containsKey(num[i])){
count.put(num[i], count.get(num[i])+1);
numDuplicate++; // keep track of duplicates
}else{
count.put(num[i], 1); // first occurence
copy[x] = num[i]; // copy unique values, empty values will be at end
x++;
}
}
// return only what is needed
int newSize = num.length - numDuplicate;
int[] copyNum = new int[newSize];
for(int i = 0; i < copyNum.length; i++){
copyNum[i] = copy[i];
}
return copyNum;
}
public static void main(String[] args) {
// sample elements
int[] nums = new int[20];
for(int i = 0; i < nums.length; i++){
nums[i] = (int)(Math.random() * 20);
}
System.out.println(Arrays.toString(nums));
System.out.println(Arrays.toString(copyArray(nums)));
}

What is the faster way to conver BigInteger to array of int?

I have BigInt
BigInteger i = new BigInteger("5876934265987526278534978564378568734564937563487564327564376534875483753475");
I need to convert it to [] int. How can I do this fast?
My method is very slow
private static int[] convertDigitsToIntArray(java.math.BigInteger x) {
String s = x.toString();
int[] result = new int[s.length()];
for (int i = 0; i < s.length(); i++) {
result[i] = Integer.parseInt(String.valueOf(s.charAt(i)));
}
return result;
}
Convert it to a string and then iterate the characters:
int[] getArr(BigInteger num)
{
String str = num.toString();
int[] arr = new int[str.length()];
for (int i=0; i<arr.length; i++)
arr[i] = str.charAt(i)-'0';
return arr;
}
May be this will help...
public static void main(String[] args) {
BigInteger i = new BigInteger("5876934265987526278534978564378568734564937563487564327564376534875483753475");
String iStr = i.toString();
int[] intArray = new int[iStr.length()];
for(int j=0; j<iStr.length(); j++) {
intArray[j] = Integer.parseInt(String.valueOf(iStr.charAt(j)));
}
}
Try using this:
private static int[] convertDigitsToIntArray(java.math.BigInteger x) {
String s = x.toString();
int[] result = new int[s.length()];
for (int i = 0; i < s.length(); i++) {
result[i] = s.charAt(i) - '0';
}
return result;
}
You can convert the BigInteger to a String, get the char array of that string and iterate over that:
java.math.BigInteger source = new java.math.BigInteger("5876934265987526278534978564378568734564937563487564327564376534875483753475");
char[] array = source.toString().toCharArray();
int[] result = new int[array.length];
for(int i=0; i<array.length; i++)
{
result[i] = array[i] - '0';
}
private static int[] convertDigitsToIntArray(java.math.BigInteger x) {
String s = x.toString();
int[] result = new int[s.length()];
for (int i = 0; i < s.length(); i++) {
// Change your code to subtract the char '0'
result[i] = s.charAt(i) - '0';
}
return result;
}

How to convert a String array to char array in Java

We are given an array of Strings and what we require is a char[], i.e, array of all characters in all the Strings
For example:
Input: [i, love, you]
output: [i, l, o, v, e, y, o, u]
First I made an array of arrays.
Then I have found the length of the required char[] array.
I have tried the following so far:
char[][] a1 = new char[str.length][];
for(int i =0;i<str.length;i++){
a1[i]=str[i].toCharArray();
}
int total=0;
for(int i =0;i<str.length;i++){
total = total + a1[i].length;
}
char[] allchar = new char[total];
for(int i=0;i<str.length;i++){
//NOW HERE I WANT TO MERGE ALL THE char[] ARRAYS TOGETHER.
//HOW SHOULD I DO THIS?
}
String[] sArray = {"i", "love", "you"};
String s = "";
for (String n:sArray)
s+= n;
char[] c = s.toCharArray();
You can do that like this
char[] allchar = new char[total]; // Your code till here is proper
// Copying the contents of the 2d array to a new 1d array
int counter = 0; // Counter as the index of your allChar array
for (int i = 0; i < a1.length; i++) {
for (int j = 0; j < a1[i].length; j++) { // nested for loop - typical 2d array format
allchar[counter++] = a1[i][j]; // copying it to the new array
}
}
You can do something like the following method..
public void converter(String[] stringArray) {
char[] charsInArray = new char[500]; //set size of char array
int counterChars = 0;
for (int i = 0; i < stringArray.length; i++) {
int counterLetters = 0; //declare counter for for amount of letters in each string in the array
for (int j = 0; j < stringArray[i].length(); j++) {
// below pretty self explanatory extracting individual strings and a
charsInArray[counterChars] = stringArray[i].charAt(counterLetters);
counterLetters++;
counterChars++;
}
}
}
String [] s = new String[]{"i", "love", "you"};
int length = 0;
for (int i = 0; i < s.length; i++) {
for (int j = 0; j < s[i].length(); j++) {
length++;
}
}
char [] c = new char[length];
int k = 0;
for (int i = 0; i < s.length; i++) {
for (int j = 0; j < s[i].length(); j++) {
c[k] = s[i].charAt(j);
k++;
}
}
for (int j = 0; j < c.length; j++) {
System.out.print("char is: " + c[j]);
}
In Java 8 we can use streams.
public char[] convert(String[] words) {
return Arrays.stream(words)
.collect(Collectors.joining())
.toCharArray();
}
Here we created a stream from an array using
Array.stream(T[] array) where T is the type of the array elements.
Than we obtain a string using Collectors.joining(). Finally we get a char array using the String's toCharArray() method.
public static void main(String[] args)
{
String sentence="Gokul Krishna is class leader";
String[] array=sentence.split("\\s");
int counter;
//String word = new String();
for(String word:array)
{
counter=0;
char[] wordArray=word.toCharArray();
for(int i=0;i<wordArray.length;i++)
{
counter++;
}
System.out.println(word+ " :" +counter);
}
}
public char[] convert(String[] arr) {
StringBuilder sb = new StringBuilder();
for (String s : arr) {
sb.append(s);
}
return sb.toString().toCharArray();
}

Categories

Resources