Below is the example of the code snippet which needs the help
Example:
[1,2,3,4,5]
if the chunk size is 1, [1,2,3,4,5]
if the chunk size is 2, [1,2] and [3,4] and [5]
if the chunk size is 3, [1,2,3] and [4,5]
if the chunk size is 4, [1,2,3,4] and [5]
Java (from comment):
int counter = 0;
for (int i=0; i<array.length; i++) {
if (count == chunksize) {
//do something and initialize
counter = 0;
}
counter++;
}
You can use Arrays.copyOfRange(int[] original, int from, int to)
The code could be something like this:
int chunk = 2; // chunk size to divide
for(int i=0;i<original.length;i+=chunk){
System.out.println(Arrays.toString(Arrays.copyOfRange(original, i, Math.min(original.length,i+chunk))));
}
Just stumbled upon this post after encountering the same question. Here is how I solved it (I used Arrays.copyOfRange():
public static int[][] splitArray(int[] arrayToSplit, int chunkSize){
if(chunkSize<=0){
return null; // just in case :)
}
// first we have to check if the array can be split in multiple
// arrays of equal 'chunk' size
int rest = arrayToSplit.length % chunkSize; // if rest>0 then our last array will have less elements than the others
// then we check in how many arrays we can split our input array
int chunks = arrayToSplit.length / chunkSize + (rest > 0 ? 1 : 0); // we may have to add an additional array for the 'rest'
// now we know how many arrays we need and create our result array
int[][] arrays = new int[chunks][];
// we create our resulting arrays by copying the corresponding
// part from the input array. If we have a rest (rest>0), then
// the last array will have less elements than the others. This
// needs to be handled separately, so we iterate 1 times less.
for(int i = 0; i < (rest > 0 ? chunks - 1 : chunks); i++){
// this copies 'chunk' times 'chunkSize' elements into a new array
arrays[i] = Arrays.copyOfRange(arrayToSplit, i * chunkSize, i * chunkSize + chunkSize);
}
if(rest > 0){ // only when we have a rest
// we copy the remaining elements into the last chunk
arrays[chunks - 1] = Arrays.copyOfRange(arrayToSplit, (chunks - 1) * chunkSize, (chunks - 1) * chunkSize + rest);
}
return arrays; // that's it
}
And the results:
chunkSize = 1
[1]
[2]
[3]
[4]
[5]
chunkSize = 2
[1, 2]
[3, 4]
[5]
chunkSize = 3
[1, 2, 3]
[4, 5]
chunkSize = 4
[1, 2, 3, 4]
[5]
chunkSize = 5
[1, 2, 3, 4, 5]
chunkSize = 6
[1, 2, 3, 4, 5]
If you don't mind importing Google Guava and converting to a List, there is a method for partitioning Lists:
https://google.github.io/guava/releases/27.1-jre/api/docs/com/google/common/collect/Lists.html#partition-java.util.List-int-
The following may achieve the desired result:
List<Integer> listToBeSplit = Arrays.asList(sourceArray);
int chunkSize = 3;
Lists.partition(listToBeSplit, chunkSize);
Using pure Java 8:
public class Chunk {
public static void main(String[] args) {
int[] input = {1,2,3,4,78,999,-1,456};
int chunkSize = 3;
int[][] chunked = chunk(input, chunkSize);
Arrays.stream(chunked)
.map(Arrays::toString)
.forEach(System.out::println);
}
public static int[][] chunk(int[] input, int chunkSize) {
return IntStream.iterate(0, i -> i + chunkSize)
.limit((long) Math.ceil((double) input.length / chunkSize))
.mapToObj(j -> Arrays.copyOfRange(input, j, j + chunkSize > input.length ? input.length : j + chunkSize))
.toArray(int[][]::new);
}
}
[1, 2, 3]
[4, 78, 999]
[-1, 456]
import java.util.Arrays;
public class ArrayChunk {
public static void main(String[] args) {
int[] array = {1,2,3,4,5};
int[][] chunks1 = ArrayChunk(array, 1);
print(chunks1);
int[][] chunks2 = ArrayChunk(array, 2);
print(chunks2);
int[][] chunks3 = ArrayChunk(array, 3);
print(chunks3);
}
public static int[][] ArrayChunk(int[] array, int chunkSize) {
int numOfChunks = (int) Math.ceil((double) array.length / chunkSize);
int[][] output = new int[numOfChunks][];
for (int i = 0; i < numOfChunks; i++) {
int start = i * chunkSize;
int length = Math.min(array.length - start, chunkSize);
int[] temp = new int[length];
System.arraycopy(array, start, temp, 0, length);
output[i] = temp;
}
//
return output;
}
private static void print(int[][] output) {
//
System.out.println("======================");
for (int[] x : output)
System.out.println(Arrays.toString(x));
}
}
======================
[1]
[2]
[3]
[4]
[5]
======================
[1, 2]
[3, 4]
[5]
======================
[1, 2, 3]
[4, 5]
Try this,
Iterate it and check to give the chunk size.
int chunkSize = userInput;
// iterate and check the condition
char[] resultArray = Arrays.copyOfRange(inputArray, start, end);
start = start + end; // check whether the start will exceeds the length of the array
public static int[][] chunkArray(int[] array, int chunkSize) {
// first we need to get number of chunks by dividing length by chunkSize.
int numOfChunks = (int)Math.ceil((double)array.length / chunkSize);
// we declare 2d array to save in the chunks
int[][] output = new int[numOfChunks][];
for(int i = 0; i < numOfChunks; i++) {
int start = i * chunkSize;
int length = Math.min(array.length - start, chunkSize);
int[] temp = new int[length];
System.arraycopy(array, start, temp, 0, length);
output[i] = temp;
}
return output;
}
for(int i=0;i<list.size();){
ArrayList<Integer>row = new ArrayList<Integer>();
int k=0;
while(k < chunksize){
chunk.add(list.get(i));
i++;
k++;
}
System.out.println(chunk);
nestedlist.add(chunk);
}
where list is a 1 dimension array and chunk is a nested array of size chunksize
In general you could use Arrays.copyOfRange to copy
This should do the trick
public static List<String> split(String string, int chunk) {
Pattern pattern = Pattern.compile("(([0-9]+,){" + (chunk - 1)
+ "}[0-9]+)|[0-9]+");
Matcher matcher = pattern.matcher(string);
List<String> result = new ArrayList<String>();
while (matcher.find())
result.add("[" + matcher.group() + "]");
return result;
}
Test code:
for (int chunkSize = 1; chunkSize < 6; ++chunkSize) {
System.out.println("test for chunk size: " + chunkSize);
for (String string : split("[1,2,3,4,5]", chunkSize))
System.out.format("\t%s\n", string);
}
Output:
test for chunk size: 1
[1]
[2]
[3]
[4]
[5]
test for chunk size: 2
[1,2]
[3,4]
[5]
test for chunk size: 3
[1,2,3]
[4]
[5]
test for chunk size: 4
[1,2,3,4]
[5]
test for chunk size: 5
[1,2,3,4,5]
public class ArrayChunk {
public static void main(String[] args) {
String[][] chunked = chunkArray("1,2,3,4,5,6,7,8,9".split(","), 2);
System.out.println("Array with chunk size 2");
Arrays.stream(chunked).forEach(strings -> System.out.println(String.join(",", strings)));
chunked = chunkArray("1,2,3,4,5,6,7,8,9".split(","), 3);
System.out.println("Array with chunk size 3");
Arrays.stream(chunked).forEach(strings -> System.out.println(String.join(",", strings)));
chunked = chunkArray("1,2,3,4,5,6,7,8,9".split(","), 4);
System.out.println("Array with chunk size 4");
Arrays.stream(chunked).forEach(strings -> System.out.println(String.join(",", strings)));
chunked = chunkArray("1,2,3,4,5,6,7,8,9".split(","), 5);
System.out.println("Array with chunk size 5");
Arrays.stream(chunked).forEach(strings -> System.out.println(String.join(",", strings)));
}
private static String[][] chunkArray(String[] array, int chunkSize) {
int chunkedSize = (int) Math.ceil((double) array.length / chunkSize); // chunked array size
String[][] chunked = new String[chunkedSize][chunkSize];
for (int index = 0; index < chunkedSize; index++) {
String[] chunk = new String[chunkSize]; // small array
System.arraycopy(array, index * chunkSize, chunk, 0, Math.min(chunkSize, array.length - index * chunkSize));
chunked[index] = chunk;
}
return chunked;
}
}
Output
Array with chunk size 2
1,2
3,4
5,6
7,8
9,null
Array with chunk size 3
1,2,3
4,5,6
7,8,9
Array with chunk size 4
1,2,3,4
5,6,7,8
9,null,null,null
Array with chunk size 5
1,2,3,4,5
6,7,8,9,null
Easy way to do so,
int loopcount = employeeList.size() / constCount;
int leftcount = employeeList.size() % constCount;
for (int i = 0; i < loopcount - 1; i++) {
//query.setParameterList("values"+i, employeeList.subList(tempCount, tempCount + constCount));
System.out.println(employeeList.subList(tempCount, tempCount + constCount));
tempCount = tempCount + 1000;
}
public class SplitArrayIntoChunks {
public static void main(String[] args) {
int[] in = {1,2,3,4,5};
chunks(in, 2);
}
private static void chunks(int[] in, int chunkSize) {
List<int[]> outList = new ArrayList<>();
int i = 0;
while (i < in.length) {
int[] out = Arrays.copyOfRange(in, i, Math.min(i + chunkSize, in.length));
outList.add(out);
out = new int[chunkSize + 1];
i += chunkSize;
}
for (int[] ol: outList) {
System.out.print("[");
Arrays.stream(ol).forEach(System.out::print);
System.out.println("]");
}
}
}
// Result: [12]
[34]
[5]
let array = [1, 2, 3, 4, 5, 6, 7, 8];
let idx = 0;
let count = 0;
let tempList = [];
let resultList = [];
let splitSize = 2
while (idx <= array.length)
{
tempList.push(array[idx++]);
count++;
if (count == splitSize)
{
resultList.push(tempList);
tempList = [];
count = 0;
}
}
if (!tempList.length)
{
resultList.push(tempList);
}
console.log(resultList);
This can be done in a few lines of code
int i=0;
while (i<array.length) {
System.out.println(Arrays.toString(Arrays.copyOfRange(array, i, Math.min(array.length, i+chunkSize))));
i+=chunkSize;
}
Q.Split the array into chunks with a specified size?
Answer:
public class SplitArray {
public static void main(String[] args) {
int[] original = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9};
int splitSize = 3;
/* expected Output
[0, 1, 2]
[3, 4, 5]
[6, 7, 8]
[9]
*/
List<int[]> list = splitArray(original, splitSize);
list.forEach(splitArray -> System.out.println(Arrays.toString(splitArray)));
}
public static List<int[]> splitArray(int[] array, int splitSize) {
List<int[]> result = new ArrayList<>();
int len=array.length;
int arr[] = null;
int size = splitSize;
int k=0;
for(int i=0;i<array.length;i++) {
if(k==0)
arr=new int[size];
arr[k]=array[i];
k++;
if(k>size-1) {
k=0;
result.add(arr);
len=len-size;
if(len<splitSize) {
size=len;
}
}
}
return result;
}
}
you can use the methode toCharArray :
// Custom input string
String str = "12345678";
// Creating array and storing the array
// returned by toCharArray() method
char[] ch = str.toCharArray();
// Lastly printing the array elements
for (char c : ch) {
System.out.println(c);
}
see more : https://www.geeksforgeeks.org/convert-a-string-to-character-array-in-java/
Related
So I have homework that asked me to:
Write a method that takes two parameters: an array of integers and an integer that represents a number of elements. It should return a two-dimensional array that results from dividing the passed one-dimensional array into rows that contain the required number of elements. Note that the last row may have less number of elements if the length of the array is not divisible by the required number of elements. For example, if the array {1,2,3,4,5,6,7,8,9} and the number 4 are passed to this method, it should return the two-dimensional array {{1,2,3,4},{5,6,7,8},{9}}.
I tried to solve it using this code:
public static int[][] convert1DTo2D(int[] a, int n) {
int columns = n;
int rows = a.length / columns;
double s = (double) a.length / (double) columns;
if (s % 2 != 0) {
rows += 1;
}
int[][] b = new int[rows][columns];
int count = 0;
for (int i = 0; i < rows; i++) {
for (int j = 0; j < columns; j++) {
if (count == a.length) break;
b[i][j] = a[count];
count++;
}
}
return b;
}
But I had a problem which is when I try to print the new array this is the output:
[[1, 2, 3, 4], [5, 6, 7, 8], [9, 0, 0, 0]]
So how can I remove the 3 zeros at the end? Just a note that I can't use any method from java.util.* or any built-in method to do this.
Change the 2D array's initialization to not contain the second dimension: new int[rows][]. Your array now has null arrays inside it. You have to initialize those in your loop: b[i]=new int[Math.min(columns,remainingCount)]; where remainingCount is the amount of numbers outside the 2d array.
Populating a 2d array with values from a 1d array as long as they are present:
public static int[][] convert1DTo2D(int[] arr, int n) {
// row count
int m = arr.length / n + (arr.length % n == 0 ? 0 : 1);
// last row length
int lastRow = arr.length % n == 0 ? n : arr.length % n;
return IntStream.range(0, m)
.mapToObj(i -> IntStream.range(0, i < m - 1 ? n : lastRow)
.map(j -> arr[j + i * n])
.toArray())
.toArray(int[][]::new);
}
public static void main(String[] args) {
int[] arr1 = {1, 2, 3, 4, 5, 6, 7, 8, 9};
int[][] arr2 = convert1DTo2D(arr1, 4);
System.out.println(Arrays.deepToString(arr2));
// [[1, 2, 3, 4], [5, 6, 7, 8], [9]]
}
See also: How to populate a 2d array with values from a 1d array?
It may be better to switch arguments in the method:
int[][] convert1DTo2D(int cols, int... arr)
to allow use of vararg.
Also, it is possible to iterate on the input array (single loop) instead of nested loops.
Example implementation:
public static int[][] convert1DTo2D(int cols, int... a) {
int lastRowCols = a.length % cols;
int rows = a.length / cols;
if (lastRowCols == 0) {
lastRowCols = cols;
} else {
rows++;
}
int[][] b = new int[rows][];
for (int i = 0; i < a.length; i++) {
int r = i / cols;
int c = i % cols;
if (c == 0) { // start of the row
b[r] = new int[r == rows - 1 ? lastRowCols : cols];
}
b[r][c] = a[i];
}
return b;
}
Adding this if-condition to your code will shorten the final array should it not be the right size:
...
final int[][] b = new int[rows][columns];
if ((a.length % columns) != 0) {
b[rows - 1] = new int[a.length % columns];
}
int count = 0;
...
% is the Modulo operator which gives you the remainder of a division of the first and second number.
9 % 4 would return 1, the exact size needed for our final array.
We then merely have to replace the final array with a new one of that size.
I have the following input
int combinationCount = 3;
int arr[] = {1, 1, 2, 2, 3};
combinationCount is {1,2,3}, combinationCount defines the number of sequence of number. For Eg: combinationCount = 3 means {1,2,3} and combinationCount = 2 means {1,2}
Array is always sorted, I want to print the output as the number of combinations as follow
[1,2,3], [1,2,3], [1,2,3], [1,2,3] //I have to iterate the whole array as it is just logic for a problem
Output Explanation (I want to print values, not index):
This is just an explanation of output which shows the index position of the value printed.
Index position of each value
[0, 2, 4], [0, 3, 4], [1, 2, 4], [1, 3, 4]
Example 2
int combinationCount = 2; // means combination is {1,2}
int arr[] = {1, 2, 2};
Print: [1,2], [1,2]
Example 3
int combinationCount = 3; // means combination is {1,2,3}
int arr[] = {1, 1, 3};
Print nothing
The program which I written is as follow:
int combinationCount = 3;
int arr[] = {1, 1, 2, 2, 3};
List<Integer> list = new ArrayList<>();
int prev = 0;
for (int i = 0; i < arr.length; i++) {
if (arr[i] == 1) {
prev = 1;
list = new ArrayList<>();
list.add(1);
for (int j = i + 1; j < arr.length; j++) {
if (arr[j] == prev + 1) {
prev = arr[j];
list.add(arr[j]);
} else if (arr[j] > (prev + 1)) {
break;
}
}
if (list.size() == combinationCount) {
System.out.print(list + ",");
}
} else {
break;
}
}
Output coming as
[1,2,3],[1,2,3]
which is not correct
Somewhere I am missing loop and how optimized code we can write? Any suggestions pls. Kindly let me know for any concern.
You can use Cartesian Product. I have used this answer as reference.
public class Test {
public static List<List<Integer>> product(List<List<Integer>> lists) {
List<List<Integer>> result = new ArrayList<>();
int solutions = lists.stream().mapToInt(List::size).reduce(1, (a, b) -> a * b);
for (int i = 0; i < solutions; i++) {
int j = 1;
List<Integer> tempList = new ArrayList<>();
for (List list : lists) {
tempList.add((Integer) list.get((i / j) % list.size()));
j *= list.size();
}
result.add(tempList);
}
return result;
}
public static void main(String[] args) {
int combinationCount = 2, count = 0;
int arr[] = {1, 1, 3};
Map<Integer, List<Integer>> map = new HashMap<>();
List<List<Integer>> combinations = new ArrayList<>();
for (Integer idx = 0; idx < arr.length; idx++) {
map.computeIfAbsent(arr[idx], k -> new ArrayList<>()).add(idx);
}
for (int i = 1; i <= combinationCount; i++) {
if (map.getOrDefault(i, null) != null)
count += 1;
}
if (count == combinationCount) {
List result = product(new ArrayList(map.values()));
System.out.println(result);
} else {
System.out.println("No combination found");
}
}
}
Output:
No combination found
Write a program to print all the LEADERS in the array. An element is leader if it is greater than all the elements to its right side. And the rightmost element is always a leader. For example int the array {16, 17, 4, 3, 5, 2}, leaders are 17, 5 and 2.
Let the input array be arr[] and size of the array be size.
o/p what i am getting is 2 5 17
Note: i want o/p in reverse order , also one below other(line break).
class LeadersInArray
{
/* Java Function to print leaders in an array */
void printLeaders(int arr[], int size)
{
int max_from_right = arr[size-1];
/* Rightmost element is always leader */
System.out.print(max_from_right + " ");
for (int i = size-2; i >= 0; i--)
{
if (max_from_right < arr[i])
{
max_from_right = arr[i];
System.out.print(max_from_right + " ");
}
}
}
public static void main(String[] args)
{
LeadersInArray lead = new LeadersInArray();
int arr[] = new int[]{16, 17, 4, 3, 5, 2};
int n = arr.length;
lead.printLeaders(arr, n);
}
}
Expected output:
17
5
2
Intead of printing those within the loop, add those to a list, and then print those separately.
Following are the changes in your code.
class LeadersInArray {
List<Integer> printLeaders(int[] arr, int size) {
List<Integer> list = new ArrayList<>();
int max_from_right = arr[size - 1];
list.add(max_from_right);
for (int i = size - 1; i >= 0; i--) {
if (max_from_right < arr[i]) {
max_from_right = arr[i];
list.add(max_from_right);
}
}
return list;
}
public static void main(String[] args) {
LeadersInArray lead = new LeadersInArray();
int arr[] = new int[]{16, 17, 4, 3, 5, 2};
List<Integer> integers = lead.printLeaders(arr, arr.length);
for(int i = integers.size()-1; i>=0 ;i--){
System.out.println(integers.get(i));
}
}
}
I am working on a method that will take an integer array and fold it in half x number of times. This method would take an integer array like this {1,2,3,4,5} and output an the array {6,6,3} if it is folded once. Or it could take the input {5,6,7,8} and output {13,13} also folded once.
If the input is folded twice then {5,6,7,8} would turn into {26}.
import java.util.Arrays;
public class Kata
{
public static int[] foldArray(int[] array, int runs)
{
int[] tempArray = array;
for(int j=0; j<runs; j++){
for(int i=0; i<tempArray.length; i++){
tempArray[i] += tempArray[tempArray.length - i];
}
}
int[] outputArray = Arrays.copyOfRange(tempArray, (tempArray.length/2));
return outputArray;
}
}
The problem with your implementation is the way in which you use tempArray:
int[] tempArray = array;
This "aliases" tempArray to the original array, so any modifications to tempArray also happen to the original array. This means that tempArray's length is not going to change from run to run, so any fold after the first one would be invalid.
You need to make tempArray a copy of the initial ⌈n/2⌉ elements on each iteration of the outer loop. To round half-length up, use this expression:
int halfLength = (tempArray.length+1)/2;
int[] tempArray = Arrays.copyOfRange(tempArray, halfLength);
This will deal with arrays of odd length.
At the end of each outer loop iteration replace array with tempArray.
You can also solve your problem recursively:
public static int[] foldArray(int[] array, int runs) {
if (runs == 0) {
return array;
}
int[] tmp;
if (array.length % 2 == 0) {
tmp = new int[array.length / 2];
for (int i = 0; i < array.length / 2; i++) {
tmp[i] = array[i];
}
} else {
tmp = new int[array.length / 2 + 1];
for (int i = 0; i < array.length / 2 + 1; i++) {
tmp[i] = array[i];
}
}
for (int i = 0; i < array.length / 2; i++) {
tmp[i] += array[array.length - i - 1];
}
return foldArray(tmp, runs - 1);
}
public static void main(String[] args) {
System.out.println(Arrays.toString(foldArray(new int[]{1, 2, 3, 4, 5}, 1)));
System.out.println(Arrays.toString(foldArray(new int[]{5, 6, 7, 8}, 1)));
System.out.println(Arrays.toString(foldArray(new int[]{5, 6, 7, 8}, 2)));
}
Note that you need to be careful with the length of the input arrays - whether it's odd or even.
Solution in JavaScript:
function fold(arr, num) {
if (num === 0 || arr.length === 1) {
return arr;
}
let result = [];
while (arr.length > 1) {
result.push(arr.shift() + arr.pop());
}
if(arr.length === 1){
result.push(arr[0]);
}
return fold(result, num - 1);
}
Example:
const arr = [1, 2, 3, 4, 5];
fold(arr, 2); --> [9,6]
I have input stream of numbers coming like
1 3 5 6 5 6 7 43 54 3 2 ....
At any point of given time how to find the last five number ?
Or you could use a circular buffer:
private class CircularBuffer {
private int[] items;
private int index = 0;
private int size = 0;
public CircularBuffer(int size) {
items = new int[size];
}
public void add(int item) {
items[index] = item;
index = (index + 1) % items.length;
size = Math.min(size + 1, items.length);
}
public int get(int i) {
if (i < 0 || i >= size)
throw new IndexOutOfBoundsException();
return items[(index - size + i + items.length) % items.length];
}
#Override
public String toString() {
StringBuilder builder = new StringBuilder("[");
for (int i = 0; i < size; ++i) {
builder.append(get(i));
builder.append(i < size - 1 ? ", " : "]");
}
return builder.toString();
}
}
Test code:
CircularBuffer b = new CircularBuffer(5);
for (int i = 1; i < 10; ++i) {
b.add(i);
System.out.println(b);
}
Output:
[1]
[1, 2]
[1, 2, 3]
[1, 2, 3, 4]
[1, 2, 3, 4, 5]
[2, 3, 4, 5, 6]
[3, 4, 5, 6, 7]
[4, 5, 6, 7, 8]
[5, 6, 7, 8, 9]
You could save them in a Stack which would be the easiest and 'best' way to do it inmho.
If you (for whatever reason) can't or don't want to use an Stack I would suggest you to implement the "push" method for Arrays:
public static void main(String[] args){
Scanner sc = new Scanner(System.in);
int[] numbers = new int[5];
while(true){ // as long as you expect numbers from your stream
push(numbers, sc.nextInt());
}
}
public static void push(int[] arr, int value){
for(int i = 1; i < arr.length; i++){
arr[i - 1] = arr[i];
}
arr[arr.length - 1] = value;
}
Assuming your Stream provides with you with Integers only, via STDIN, one per line - the numbers array now holds the last 5 inputs for you (or 0 as a default value in case less than 5 values arrived so far).
Greetings Tim