Read groups of N adjacent elements from an array - java

[A, B, C, D, E, F]
I need to get adjacent values from above array.
Adjacent count can vary
say
if adjcnt = 2
Then I should get like this
tuple 1 = A,B
tuple 2 = C,D
tuple 3 = E,F
If adjcnt = 3
tuple 1 = A,B,c
tuple 2 = D,E,F
My code
for (int i = 0; i < arr.length; i++) {
if(i < adjcnt){
if(i==0){
csv = arr[i];
}
else{
csv += ","+arr[i];
}
}
System.out.println("csv---> "+csv);
}
This prints only 2 elements. I need to loop till my arr is empty
Some where my logic is not right.
Please Advice

Change your this code:-
for (int i = 0; i < arr.length; i++) {
if(i < adjcnt){
if(i==0){
csv = arr[i];
}
else{
csv += ","+arr[i];
}
}
System.out.println("csv---> "+csv);
}
to the following
for (int i = 0; i < arr.length; i++) {
if((i % adjcnt) < adjcnt){
if((i % adjcnt)==0){
csv = arr[i];
}
else{
csv += ","+arr[i];
}
}
System.out.println("csv---> "+csv);
}

#include<stdio.h>
int main()
{
int arr[6] = {1,2,3,4,5,6};
int i = 0;
int adjacent = 2;
for(i=0;i<6;i++)
{
if( i% adjacent == 0 ) {
printf("\n");
}
printf("%d",arr[i]);
}
return 0;
}

You can try this way too.
int adjcnt = 3;
String[] arr = {"A", "B", "C", "D", "E", "F"};
for(int i=0; i< arr.length; i= i + adjcnt){
System.out.println(Arrays.toString(Arrays.copyOfRange(arr, i, i+adjcnt)));
//here it will copy your original array between given indexes.
}
out put:
[A, B, C]
[D, E, F]

Unmesha, you can use the following code for your expected output
public class Adjacent {
public static void main(String args[]) {
char[] test = { 'a', 'b', 'c', 'd', 'e', 'f' };
int adjcnt = 3;
StringBuilder csv = new StringBuilder();
int tuplecount = 1;
for (int i = 0; i < test.length; i++) {
if (i % adjcnt == 0 || i == 0) {
if (i != 0)
csv.append("\n");
csv.append("tuple ");
csv.append(tuplecount);
csv.append("=");
csv.append(test[i]);
} else {
csv.append(",");
csv.append(test[i]);
}
}
System.out.println(csv.toString());
}
}
Please update me if this code works out for you

Related

removing the duplicates from array

I have homework about arrays in Java and I am stuck on this question.
Fill in the body of the program below, which removes duplicate values from the sorted array input. Your solution should set the variable result to the number of values remaining after the duplicate values have been removed. For example, if input is (0,1,1,2,3,3,3,4,4), the first five values of input after removing the duplicates should be (0,1,2,3,4), and the value of result should be 5.
Here's my code:
import java.util.Scanner;
public class RemoveDups {
public static void main (String[] args) {
Scanner scan = new Scanner(System.in);
int[] input = 0,1,1,2,3,3,3,4,4;
int result;
int count = input[0];
result++;
String count1="";
int result2=0;
count1=count1+count;
input[0]=Integer.parseInt(count1);
count1="";
for (int j = 1; j <input.length-1;j++ ) {
if (count != input[j+1] && result2 == 0||count != input[j-1] &&result2==0 ) {
input[j] = count;
result++;
count = input[j + 1];
count1=count1+count;
input[j]=Integer.parseInt(count1);
count1="";
}
}
for (int i = 0; i < result; i++) {
System.out.println(input[i]);
}
}
}
}
I can't do this exercise. i have left always the last cell in array that is different from all another cells and this code not working for me.
public static int removeDuplicateElements(int arr[], int n){
if (n==0 || n==1){
return n;
}
int j = 0;
for (int i=0; i < n-1; i++){
if (arr[i] != arr[i+1]){
arr[j++] = arr[i];
}
}
arr[j++] = arr[n-1];
return j;
}
public static void main(String args []) {
int arr[] = {0,1,1,2,3,3,3,4,4};
int length = arr.length;
length = removeDuplicateElements(arr, length);
for (int i=0; i<length; i++)
System.out.print(arr[i]+" ");
}
Answer will be 0 1 2 3 4
Please refer following link.
Remove Duplicate Element in Array using separate index
I am not sure if you needed a filtered array or just the result value. The below will give you result value.
Since this is homework, I suggest you work on the below logic to create the non duplicate array.
int result = 1;
if(input == null || input.length == 0){
result = 0;
}
else{
for(int i = 1; i < input.length; i++){
if(input[i-1] != input[i]){
result++;
}
}
}

Characters in array are being removed when sorting a string

I am writing a class to print the given string to lexicographical order but in the final method 'reverseOrder()' the array is automatically deleting values from it (I suppose). The method reverseOrder is deleting some characters for selected string such as "dkhc". Thanks
Debugging shows the values are correctly added to the array.
public class LexicalOrder {
static String biggerIsGreater(String w) {
String finalString = "";
char[] charArr = w.toCharArray();
int largestX = -1;
// Find the largest x such that P[x]<P[x+1].
// (If there is no such x, P is the last permutation.)
for (int i = 0; i < charArr.length - 1; i++) {
if (charArr[i] < charArr[i + 1]) {
largestX = i;
}
}
if (largestX == -1) {
finalString = "no answer";
}
int largestY = -1;
if (largestX != -1) {
for (int j = 0; j < charArr.length; j++) {
if (charArr[largestX] < charArr[j]) {
largestY = j;
}
}
charArr = swap(charArr, largestX, largestY);
charArr = reverseOrder(charArr, largestX + 1);
finalString = new String(charArr);
}
return finalString;
}
// Method to swap characters in index largestX and largestY
public static char[] swap(char[] a, int largestX, int largestY) {
char temp = a[largestY];
a[largestY] = a[largestX];
a[largestX] = temp;
return a;
}
// Method to reverse the order of the array from the index
// largestX + 1 to n (n being last element of array)
public static char[] reverseOrder(char[] a, int index) {
int step = 0;
char[] newArr = new char[a.length];
for (int j = 0; j < index; j++) {
System.out.println(j);
newArr[j] = a[j]; // adding elements to new arr till index=largestX
System.out.println(newArr[j] = a[j]);
}
for (int i = index; i < a.length; i++) {
System.out.println(i);
newArr[index] = a[a.length - step - 1]; // adding remaining values but with reversing order
System.out.println(newArr[index] = a[a.length - step - 1]);
step++;
}
for (char c : newArr)
System.out.println(c);
return newArr;
}
public static void main(String[] args) {
System.out.println(biggerIsGreater("dkhc"));
}
}
What is expected is = hcdk.
But what I get is = hk
I ran the method to check and it clearly adds those elements to the "newArr" array in method 'reverseOrder()' as shown below.
0
h
1
c
2
d
3
k
Output - hk (and two spaces)
The two characters are replaced by two spaces for some reason.
P.S : I am following the steps mentioned here link
Note: It works for some words such as "lmno,dcba,etc"
What you have missed is index++. In reverseOrder method increment index++ will give you hcdk expected output.
public static char[] reverseOrder(char[] a, int index) {
int step = 0;
char[] newArr = new char[a.length];
for (int j = 0; j < index; j++) {
System.out.println(j);
newArr[j] = a[j]; // adding elements to new arr till index=largestX
System.out.println(newArr[j] = a[j]);
}
for (int i = index; i < a.length; i++) {
System.out.println(i);
newArr[index] = a[a.length - step - 1]; // adding remaining values
// but with reversing order
System.out.println(newArr[index] = a[a.length - step - 1]);
step++;index++;
}
for (char c : newArr)
System.out.println(c);
return newArr;
}
In your case index value is not getting incremented due to which 2 and 3 item in an array are blank.

JAVA - Compare two arrays and create a new array with only the unique values from the first

I have to solve an exercise with the following criteria:
Compare two arrays:
int[] a1 = {1, 3, 7, 8, 2, 7, 9, 11};
int[] a2 = {3, 8, 7, 5, 13, 5, 12};
Create a new array int[] with only unique values from the first array. Result should look like this: int[] result = {1,2,9,11};
NOTE: I am not allowed to use ArrayList or Arrays class to solve this task.
I'm working with the following code, but the logic for the population loop is incorrect because it throws an out of bounds exception.
public static int[] removeDups(int[] a1, int[] a2) {
//count the number of duplicate values found in the first array
int dups = 0;
for (int i = 0; i < a1.length; i++) {
for (int j = 0; j < a2.length; j++) {
if (a1[i] == a2[j]) {
dups++;
}
}
}
//to find the size of the new array subtract the counter from the length of the first array
int size = a1.length - dups;
//create the size of the new array
int[] result = new int[size];
//populate the new array with the unique values
for (int i = 0; i < a1.length; i++) {
int count = 0;
for (int j = 0; j < a2.length; j++) {
if (a1[i] != a2[j]) {
count++;
if (count < 2) {
result[i] = a1[i];
}
}
}
}
return result;
}
I would also love how to solve this with potentially one loop (learning purposes).
I offer following soulution.
Iterate over first array, and find out min and max it's value.
Create temporary array with length max-min+1 (you could use max + 1 as a length, but it could follow overhead when you have values e.g. starting from 100k).
Iterate over first array and mark existed values in temorary array.
Iterate over second array and unmark existed values in temporary array.
Place all marked values from temporary array into result array.
Code:
public static int[] getUnique(int[] one, int[] two) {
int min = Integer.MAX_VALUE;
int max = Integer.MIN_VALUE;
for (int i = 0; i < one.length; i++) {
min = one[i] < min ? one[i] : min;
max = one[i] > max ? one[i] : max;
}
int totalUnique = 0;
boolean[] tmp = new boolean[max - min + 1];
for (int i = 0; i < one.length; i++) {
int offs = one[i] - min;
totalUnique += tmp[offs] ? 0 : 1;
tmp[offs] = true;
}
for (int i = 0; i < two.length; i++) {
int offs = two[i] - min;
if (offs < 0 || offs >= tmp.length)
continue;
if (tmp[offs])
totalUnique--;
tmp[offs] = false;
}
int[] res = new int[totalUnique];
for (int i = 0, j = 0; i < tmp.length; i++)
if (tmp[i])
res[j++] = i + min;
return res;
}
For learning purposes, we won't be adding new tools.
Let's follow the same train of thought you had before and just correct the second part:
// populate the new array with the unique values
for (int i = 0; i < a1.length; i++) {
int count = 0;
for (int j = 0; j < a2.length; j++) {
if (a1[i] != a2[j]) {
count++;
if (count < 2) {
result[i] = a1[i];
}
}
}
}
To this:
//populate the new array with the unique values
int position = 0;
for (int i = 0; i < a1.length; i++) {
boolean unique = true;
for (int j = 0; j < a2.length; j++) {
if (a1[i] == a2[j]) {
unique = false;
break;
}
}
if (unique == true) {
result[position] = a1[i];
position++;
}
}
I am assuming the "count" that you implemented was in attempt to prevent false-positive added to your result array (which would go over). When a human determines whether or not an array contains dups, he doesn't do "count", he simply compares the first number with the second array by going down the list and then if he sees a dup (a1[i] == a2[j]), he would say "oh it's not unique" (unique = false) and then stop going through the loop (break). Then he will add the number to the second array (result[i] = a1[i]).
So to combine the two loops as much as possible:
// Create a temp Array to keep the data for the loop
int[] temp = new int[a1.length];
int position = 0;
for (int i = 0; i < a1.length; i++) {
boolean unique = true;
for (int j = 0; j < a2.length; j++) {
if (a1[i] == a2[j]) {
unique = false;
break;
}
}
if (unique == true) {
temp[position] = a1[i];
position++;
}
}
// This part merely copies the temp array of the previous size into the proper sized smaller array
int[] result = new int[position];
for (int k = 0; k < result.length; k++) {
result[k] = temp[k];
}
Making your code work
Your code works fine if you correct the second loop. Look at the modifications I did:
//populate the new array with the unique values
int counter = 0;
for (int i = 0; i < a1.length; i++) {
for (int j = 0; j < a2.length; j++) {
if (a1[i] == a2[j]) {
result[counter] = a1[i];
counter++;
}
}
}
The way I would do it
Now, here is how I would create a method like this without the need to check for the duplicates more than once. Look below:
public static int[] removeDups(int[] a1, int[] a2) {
int[] result = null;
int size = 0;
OUTERMOST: for(int e1: a1) {
for(int e2: a2) {
if(e1 == e2)
continue OUTERMOST;
}
int[] temp = new int[++size];
if(result != null) {
for(int i = 0; i < result.length; i++) {
temp[i] = result[i];
}
}
temp[temp.length - 1] = e1;
result = temp;
}
return result;
}
Instead of creating the result array with a fixed size, it creates a new array with the appropriate size everytime a new duplicate is found. Note that it returns null if a1 is equal a2.
You can make another method to see if an element is contained in a list :
public static boolean contains(int element, int array[]) {
for (int iterator : array) {
if (element == iterator) {
return true;
}
}
return false;
}
Your main method will iterate each element and check if it is contained in the second:
int[] uniqueElements = new int[a1.length];
int index = 0;
for (int it : a1) {
if (!contains(it, a2)) {
uniqueElements[index] = it;
index++;
}
}

How can I check the number of times a character is shown in the array?

I am trying to create a program that will tell me how many times a letter appears in the array, so if the array contains {'a','c','b','a','b','a'} it will output:
a: 3
c: 1
b: 2.
I am building this program so I can learn how to think, so I want to do it with the basics only. No Hashmap and other more advanced things.
Edit: here is my answer, I succeeded create the program without Hashmap:
public class arrays5 {
public static void main(String[] args) {
char [] arr = {'a', 'b', 'a', 'c', 'b','a'};
char [] letters = new char[arr.length];
int count = 0;
char ch = '_';
boolean isInArray;
for (int i=0; i < arr.length; i++) {
isInArray = false;
for (int j = 0; j < arr.length; j++) {
if (arr[i] == letters[j])
isInArray = true;
}
if (!isInArray)
letters[i] = arr[i];
}
int amountOfLetters = 0;
for (int i = 0; i < letters.length; i++) {
if (letters[i] != '\0')
amountOfLetters++;
}
int index = 0;
char [] newLetters = new char[amountOfLetters];
for (int i = 0; i < letters.length; i++) {
if (letters[i] != '\0') {
newLetters[index] = letters[i];
index++;
}
}
for (int k = 0; k < newLetters.length; k++) {
for(int i=0;i<arr.length;i++){
ch = arr[i];
count = 0;
for(int j=i;j<arr.length;j++){
if(arr[i] == arr[j])
count++;
}
if (ch == newLetters[k])
System.out.println(ch + ": " + count);
}
}
}
}
I created the temporary arrays so I can know when a char has already output and it will not show the same char more than once, but it didn't help, the output of this program is:
I would suggest using a HashMap.
Quick demo:
import java.util.HashMap;
public class Demo {
public static void main(String[] args){
char[] inputs = {'a','b','a','b','c','a'};
HashMap<Character, Integer> map = new HashMap<>();
for(Character c : inputs){
if(map.containsKey(c)){
Integer i = map.get(c);
i++;
map.put(c, i);
}
else{
map.put(c, 1);
}
}
System.out.println(map);
}
}
will output:
{b=2, c=1, a=3}
Where they key is your char and the number indicates how often it was in your array.
You can simply do this by using an array index for each element. This way you don't have to know the input but assumed all are small caps.
public class Demo {
public static void main(String[] args){
int[] count= new int[26]; // 26 elements for 26 letters
char[] inputs = {'a','b','a','b','c','a'}; // example input
for(Character c : inputs){
count[c-'a'] ++;
// if c='b', then c-'a' returns 1, thus increments the count[1].
}
for (int i=0; i<26; i++){
// using if condition I only print the previously encountered letters
if(count[i]>0)
System.out.println((char)(i+'a')+":"+count[i]);
}
}
}
This way time complexity is really low (Only O(number_of_inputs)).
I won't give you a full solution, however I'll try to guide you.
You can make a HashMap<Character, Integer>.
If the char already appears in the map, increment it's key by one, otherwise, add it to the map.
For example:
put('C', 1);
Then, assume it's 'C' again, you can do:
put('C', get('C') + 1);
Since the key of 'C' is 1, now when you put it, the key will be 2.
you can read the character using the scanner.next()
char c = scan.next().charAt(0);
you can change your code like below
Scanner scan = new Scanner(System.in);
System.out.println("Enter size of array : ");
int n = scan.nextInt();
char[] arr = new char[n];
//Read inputs to array
for(int i = 0; i < n; i++)
{
arr[i] = scan.next().charAt(0);
}
//Main Logic
to optimize your code (Main Logic ) you can use hash table visit [http://docs.oracle.com/javase/7/docs/api/java/util/Hashtable.html]
In java 8 it's one line:
return Arrays.stream(arr).collect(Collectors.groupingBy(String::valueOf, Collectors.counting()).get(input);

How do I remove duplicates from two arrays?

I need to have an algorithm that changes values in one array if it is in the second array. The result is that the first array should not have any values that are in the second array.
The arrays are of random length (on average ranging from 0 to 15 integers each), and the content of each array is a list of sorted numbers, ranging from 0 to 90.
public void clearDuplicates(int[] A, int[] B){
for(int i = 0; i < A.length; i++){
for(int j = 0; j < B.length; j++)
if(A[i] == B[j])
A[i]++;
}
}
My current code does not clear all of the duplicates. On top of that it might be possible it will creat an index out of bounds, or the content can get above 90.
Although your question is not very clear, this might do the job. Assumptions:
The number of integers in A and B is smaller than 90.
The array A is not sorted afterwards (use Arrays.sort() if you wish to
fix that).
The array A might contain duplicates within itself afterwards.
public void clearDuplicates(int[] A, int[] B) {
// Initialize a set of numbers which are not in B to all numbers 0--90
final Set<Integer> notInB = new HashSet<>();
for (int i = 0; i <= 90; i++) {
notInB.add(i);
}
// Create a set of numbers which are in B. Since lookups in hash set are
// O(1), this will be much more efficient than manually searching over B
// each time. At the same time, remove elements which are in B from the
// set of elements not in B.
final Set<Integer> bSet = new HashSet<>();
for (final int b : B) {
bSet.add(b);
notInB.remove(b);
}
// Search and remove duplicates
for (int i = 0; i < A.length; i++) {
if (bSet.contains(A[i])) {
// Try to replace the duplicate by a number not in B
if (!notInB.isEmpty()) {
A[i] = notInB.iterator().next();
// Remove the added value from notInB
notInB.remove(A[i]);
}
// If not possible, return - there is no way to remove the
// duplicates with the given constraints
else {
return;
}
}
}
}
You can do it just by using int[ ] although it's a bit cumbersome. The only constraint is that there may not be duplicates within B itself.
public void clearDuplicates(int[] A, int[] B) {
//Number of duplicates
int duplicate = 0;
//First you need to find the number of duplicates
for (int i = 0; i < A.length; i++) {
for (int j = 0; j < B.length; j++)
if (A[i] == B[j])
duplicate++;
}
//New A without duplicates
int[] newA = new int[A.length-duplicate];
//For indexing elements in the new A
int notDuplicate = 0;
//For knowing if it is or isn't a duplicate
boolean check;
//Filling the new A (without duplicates)
for (int i = 0; i < A.length; i++) {
check = true;
for (int j = 0; j < B.length; j++) {
if (A[i] == B[j]) {
check = false;
notDuplicate--;//Adjusting the index
}
}
//Put this element in the new array
if(check)
newA[notDuplicate] = A[i];
notDuplicate++;//Adjusting the index
}
}
public class DuplicateRemove {
public static void main(String[] args) {
int[] A = { 1, 8, 3, 4, 5, 6 };
int[] B = { 1, 4 };
print(clear(A, B));
}
public static int[] clear(int[] A, int[] B) {
int a = 0;
for (int i = 0; i < A.length; i++) {
for (int j = 0; j < B.length; j++) {
if (A[i] == B[j]) {
a++;
for (int k = i; k < A.length - a; k++) {
A[k] = A[k + 1];
}
}
}
}
int[] C = new int[A.length - a];
for (int p = 0; p < C.length; p++)
C[p] = A[p];
return C;
}
public static void print(int[] A) {
for (int i = 0; i < A.length; i++)
System.out.println("Element: " + A[i]);
}
}
Here is an example.. I compiled and its working. For any question just let me know :)
maybe you should try the following code:
public void clear (int[] A, int[] B)
{
for (int i=0; i<A.length;i++)
{
for (int j=0; j<B.length; j++)
if(A[i]==B[j])
{
for (int k=i; k<A.length;k++)
A[k]=A[k+1];
j=B.length-1; //so that the cycle for will not be executed
}
}
}

Categories

Resources