I have a 2D array called board:
2 3 4 5 6 7
3 5 6 7 8 5
3 5 6 7 8 7
I want the value at row 2 and col 3 so I do:
Scanner keyboard = new Scanner(System.in);
int row = keyboard.nextInt()-1;
int col = keyboard.nextInt()-1;
System.out.println(board[row][col]);
I input 2 and 3 which gave me 6, but what I want to do it instead of having row name as numbers such as 0, 1, 2..., I want them to be A, B, C, so it will look like this:
0 1 2 3 4 5 - "name"
A 2 3 4 5 6 7
B 3 5 6 7 8 5
C 3 5 6 7 8 7
So instead of entering 2 and 3 for row and col I will enter B3.
How do I change that?
You can read the "B3" in a string. For the row, 'B' - 'A' now is the index to your board; for the column index, use '3' - '0'.
Remember characters differ from the digits by only an offset.
You can use Map to accomplish that:
Map<String, int[]> matrix = new HashMap<>();
// I assume you have a process to store the input data into the Map
matrix.put("A", new int[]{ 2, 3, 4, 5, 6, 7 });
matrix.put("B", new int[]{ 3, 5, 6, 7, 8, 5 });
matrix.put("C", new int[]{ 3, 5, 6, 7, 8, 7 });
Scanner keyboard = new Scanner(System.in);
String row = keyboard.next();
int col = keyboard.nextInt() - 1;
System.out.println(matrix.get(row)[col]);
Hope it helps!
Well you just have to write a method that changes a 2 char string input into 2 numbers in which you then use to print out the number you want.
ex: "A1"
if the first char = "A", i = 0;
if the second char = "1", j = 1;
hope this helps
Related
I have a string 123456789I also have a bunch of numbers (identities, if you will) such as
2 1 1 1 2 2
2 1 1 1 3 1
2 1 1 2 1 2
2 1 1 2 2 1
2 1 1 3 1 1
The idea is, these numbers specify the groups of digits that should be extracted from the string (left to right order, if that matters). Therefore, a number like 2 3 2 1 1 means Output the first 2 characters, then the next 3 characters, then the next 2 characters, then the next 1 character, then finally the last 1 character remaining.So as examples,2 1 1 1 2 2 should output 12 3 4 5 67 892 1 1 1 3 1 should output 12 3 4 5 678 92 1 1 2 1 2 should output 12 3 4 56 7 892 1 1 2 2 1 should output 12 3 4 56 78 92 1 1 3 1 1 should output 12 3 4 567 8 9
I tried working with the method charAt() but it would seem that's just not for me
public static void main(String[] args) {
String mine = "123456789";
System.out.println(mine.charAt(2)+"\t"+mine.charAt(1)+"\t"+
mine.charAt(1)+"\t"+mine.charAt(1)+"\t"+mine.charAt(2)
+"\t"+mine.charAt(2));
}
The above gives an unwanted output
3 2 2 2 3 3
How do I solve this rather tricky (for me) issue ?
This should do the work for you.
public static void main(String[] args){
String identities = "2 1 1 1 3 1";
String stringToBreakApart = "123456789";
StringBuilder sb = new StringBuilder();
int currentPosition = 0;
for(String identityString : identities.split(" ")){
int identity = Integer.parseInt(identityString);
sb.append(stringToBreakApart, currentPosition, currentPosition += identity);
sb.append(" ");
}
System.out.println(sb.toString());
}
I've given a simple trial on it. Does below give you some help?
public static void main(String[] args) {
int[][] identitiesBunch = new int[][] {
{2, 1, 1, 1, 2, 2},
{2, 1, 1, 1, 3, 1},
{2, 1, 1, 2, 1, 2},
{2, 1, 1, 2, 2, 1},
{2, 1, 1, 3, 1, 1}
};
String mine = "123456789";
char[] numbers = mine.toCharArray();
int index = 0;
for (int[] identities: identitiesBunch) {
for (int id: identities ) {
for (int i = 0 ; i < id; i++)
System.out.print(numbers[index++]);
System.out.print(' ');
}
index = 0;
System.out.println();
}
}
Suppose this, I obtain an array of Integer Wraps Objects...
Integer[] p = new Integer[]{7, 5, 3, 2}; //Variable Length
Now, I want create an Array of ArrayList with next respective values.
2
3
3, 2
5
5, 2
5, 3
5, 3, 2
7
7, 2
7, 3
7, 3, 2
7, 5
7, 5, 2
7, 5, 3, 2
7, 5, 3, 2
What code helps me to create an array with value shown before?
In this code I tried generate:
public static void generateTable(int index, int[] current, int[] values) {
if(index == values.length) {
for(int i = 0; i < values.length; i++) {
System.out.print((current[i]) + " ");
}
System.out.println();
} else {
current[index] = 0;
generateTable(index + 1, current, values);
current[index] = values[index];
generateTable(index + 1, current, values);
}
}
This code only show the combination I want to extract only the before combinations (Except Zero values).
0 0 0 0
0 0 0 2
0 0 3 0
0 0 3 2
0 5 0 0
0 5 0 2
0 5 3 0
0 5 3 2
7 0 0 0
7 0 0 2
7 0 3 0
7 0 3 2
7 5 0 0
7 5 0 2
7 5 3 0
7 5 3 2
I test with this code:
java.util.List<Integer>[] arr = new ArrayList[p.length];
for( int i = 0; i < p.length; i++) {
arr[i] = new ArrayList();
for (int j = 0; j <= i; j++) {
arr[i].add(p[j]);
}
System.out.println(arr[i]);
}
The output for before code is not working properly, is not recursive and doesn't show the omitted value like [5, 3, 2] or [7, 5, 2] , etc!
[7]
[7, 5]
[7, 5, 3]
[7, 5, 3, 2]
Instead of directly converting arrays into List. When you do that 0s will also be picked up and placed in your list. Iterate through each index of your array, find only non-zero elements and put them into your list. Can this help?
Given an array of positive integers representing terrain heights (in 2-d, ala Super Mario)) and an integer representing a flat sea level, return a container of integers representing the volume of each unique body of water.
Please do not solve the whole problem for me!
I have a few questions:
Lets take an example first.
int [] arr = {4, 3, 5, 6, 4, 2};
int sea_level = 4;
The way it is set up is like this:
6
5 6
4 5 6 4 2
4 3 5 6 4 2
4 3 5 6 4 2
4 3 5 6 4 2
Q So we can't cross over 4 right?
So we have the ranges, [4, 3] and [4, 2] (after the [5, 6] range).
But how do I calculate the volume?
Arraylist<Integer> list = new Arraylist<>();
int volume = 0;
for(int i = 0; i < arr.length; i++){
if(arr[i] <= sea_level){
volume += arr[i];
} else{
list.add(volume); //volume for one block, then reset down.
volume = 0; //loop starts with the next one.
}
}
Is this the way to go about it? I don't understand the problem.
Given your example:
6
5 6 5
4 5 6 5
4 3 5 6 5
4 3 5 6 2 5
4 3 5 6 2 1 5
The water line is at 4, so:
6
5 6 5
~~~~~~~~~~~~5
4 5 6 5
4 3 5 6 5
4 3 5 6 2 5
4 3 5 6 2 1 5
Which makes the water volume the holes beneath the water line, or:
6
5 6 5
~~~~~~~~~~~~5
4 W 5 6 W W 5
4 3 5 6 W W 5
4 3 5 6 2 W 5
4 3 5 6 2 1 5
or, 1 cube of water, and then 5 cubes of water.
Now, how do you calculate that... you need the volume.
The volume is measured between the waterline (4) and the terrain height...
So to measure the volume: sea_level - a[i]
I'm trying to split the array into odd and even numbers. Note that sorting numbers in the final result does not matter. I'm compiling the code and the output contains some bug. My code arranges odd numbers correctly while the even numbers are giving me some trouble. Could somebody please help me out with the arrangement of even numbers?
Basically, I arrange odd numbers in the left side of the array and have oddPos = 0 in the beginning; even numbers are in the right side and the positioning starts from the very end of the array evenPos = myArray.length - 1.
public class EvenOddArray {
public static void main(String[] args){
int[] myArray = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
int oddPos = 0;
int evenPos = myArray.length - 1;
for(int i = 0; i < myArray.length; i++){
if(myArray[i] % 2 == 0){
myArray[evenPos] = myArray[i];
evenPos--;
}
else{
myArray[oddPos] = myArray[i];
oddPos++;
}
}
for(int i = 0; i < myArray.length; i++){
System.out.print(myArray[i] + " ");
}
}
}
Output:
1 3 5 7 2 4 6 6 4 2
int current = 0;
int evenPos = myArray.Length - 1;
while (current < evenPos) {
if (myArray[current] % 2 == 0) {
swap(myArray, evenPos, current);
evenPos--;
} else {
current++;
}
}
A squeezed funny version:
for (int curPos=0, evenPos=myArray.length-1; curPos < evenPos;)
if (myArray[curPos] % 2 == 0)
swap(myArray, evenPos--, curPos);
else
curPos++;
More fun version:
for (int curPos=0, evenPos=myArray.length-1; curPos < evenPos;)
swap(myArray, curPos, myArray[curPos]%2==0 ? evenPos-- : curPos++);
explanation:
You don't have to swap values when the number is odd. you only
increase the current counter.
you can't use the for loop counter as an index to the array too. to
not miss the numbers that gets swapped to the counter index not
processed. this is the mistake that other answers didn't cover.
Actually you are editing the same myArray array while reading from it. So what happens is,
You insert 6 into the myArray[7] th position, in the 6th iteration of the loop. So, during the 7th iteration when you read the myArray[7], it is 6. Not 8. Because, you have over written 8 with 6 in the previous iteration.
Therefore, use a separate array to hold the results. Hope you get the point.
You can do something like this,
int[] myArray = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
int[] resultArray = new int[myArray.length];
int oddPos = 0;
int evenPos = myArray.length - 1;
for(int i = 0; i < myArray.length; i++){
if(myArray[i] % 2 == 0){
resultArray[evenPos] = myArray[i];
evenPos--;
}
else{
resultArray[oddPos] = myArray[i];
oddPos++;
}
}
Lets see what happens with each Iteration of your for loop.
Original: 1 2 3 4 5 6 7 8 9 10
1st Iter: 1 2 3 4 5 6 7 8 9 10
2nd Iter: 1 2 3 4 5 6 7 8 9 2
3rd Iter: 1 3 3 4 5 6 7 8 9 2
4th Iter: 1 3 3 4 5 6 7 8 4 2
5th Iter: 1 3 5 4 5 6 7 8 4 2
6th Iter: 1 3 5 4 5 6 7 6 4 2
7th Iter: 1 3 5 7 5 6 7 6 4 2
8th Iter: 1 3 5 7 5 6 6 6 4 2
9th Iter: 1 3 5 7 5 4 6 6 4 2
10th Iter: 1 3 5 7 2 4 6 6 4 2
As you can see, you are modifying the array "inplace". You are modifying the array without using all the values. For example, look at 9, It gets over written before it is ever accessed. So, your algo is wrong.
Suggestions:
Use a new array to hold the results as in tibzon's answer
Use swapping instead of overwriting. You have to update your algo accordingly. I was going to provide one. But Murenik already provided one.
Here is my optimized version, which uses around half of the swaps compared to the #hasan83 version.
int n = myArray.length;
int oddPos = 0;
int evenPos = n - 1;
while (true) {
while (oddPos < n && myArray[oddPos] % 2 == 1) {
oddPos++;
}
while (evenPos >= 0 && myArray[evenPos] % 2 == 0) {
evenPos--;
}
if (oddPos >= evenPos) break;
swap(myArray, oddPos, evenPos);
}
Let's say I have a list [x1, x2, x3] where x1, x2, and x3 can take on any value between 1 and 5.
I want to iterate over every possible list that can be created (From [1, 1, 1], [1, 1, 2], . To [5, 5, 5]). This is an easy problem with only 3 elements in the list.
You can do something like this:
for x = 1; x <= 5; x++;
for y = 1; y <= 5; y++;
...
for q = 1; q <= 5; q++;
create list [x, y, ..., q];
do something with the list;
However, how do you iterate over every possible list where the number of elements is over like 10?
Edi: I've added Java as a constraint. I just want to see how this would be done without too many fancy library calls.
Edit2: What I am really looking for is some algorithm to do this, not what sort of libraries can be used to do it. But what I'm looking for is really a language-independent algorithm.
Using Guava you can do it easily:
public static void main(String[] args) {
int lowerBound = 1;
int upperBound = 5;
int setSize=3;
ContiguousSet<Integer> integers = ContiguousSet.create(Range.closed(lowerBound, upperBound), DiscreteDomain.integers());
List<Set<Integer>> sets = Lists.newArrayList();
for (int i = 0; i < setSize; i++) {
sets.add(integers);
}
Set<List<Integer>> cartesianProduct = Sets.cartesianProduct(sets);
for (List<Integer> list : cartesianProduct) {
System.out.println(list);
}
}
Which prints:
[1, 1, 1]
[1, 1, 2]
[1, 1, 3]
[1, 1, 4]
[1, 1, 5]
...
[5, 5, 4]
[5, 5, 5]
Logic :
In arr[x1 x2 x3]; all x1, x2, x3 can have values from 1 to 5. Which means every position in array can have value from 1 to 5. For a value at current position all the values are possible at next position.
suppose at 0 position of array value stored is 1.
[1 _ _] _ represent there is no value.
values for the next position : [1 1 _] , [1 2 _] ,[1 3 _] ,[1 3 _] ,[1 4 _],[1 5 _].
So iterate over current position to store the different possible values from 1 to 5 at current position and for each value call the permutate function again with current position value incremented by 1 for iterating all possible values from 1 to 5 at next position .
Code :
public class permutation {
static int limit;
public static void permutate(int arr[],int curPos)
{
int i;
if(curPos==arr.length)
{
for(i=0;i<arr.length;i++)
{
System.out.print(arr[i] + "\t");
}
System.out.println("");
return;
}
for(i=1;i<=limit;i++)
{
arr[curPos]=i;
permutate(arr,curPos+1);
}
}
public static void main(String[] args) {
int arr[] = new int[3];
limit = 5;
permutate(arr,0);
}
}
Output :
1 1 1
1 1 2
1 1 3
1 1 4
1 1 5
1 2 1
1 2 2
1 2 3
1 2 4
1 2 5
1 3 1
1 3 2
1 3 3
1 3 4
1 3 5
1 4 1
1 4 2
1 4 3
1 4 4
1 4 5
1 5 1
1 5 2
1 5 3
1 5 4
1 5 5
2 1 1
2 1 2
2 1 3
2 1 4
2 1 5
2 2 1
2 2 2
2 2 3
2 2 4
2 2 5
2 3 1
2 3 2
2 3 3
2 3 4
2 3 5
2 4 1
2 4 2
2 4 3
2 4 4
2 4 5
2 5 1
2 5 2
2 5 3
2 5 4
2 5 5
3 1 1
3 1 2
3 1 3
3 1 4
3 1 5
3 2 1
3 2 2
3 2 3
3 2 4
3 2 5
3 3 1
3 3 2
3 3 3
3 3 4
3 3 5
3 4 1
3 4 2
3 4 3
3 4 4
3 4 5
3 5 1
3 5 2
3 5 3
3 5 4
3 5 5
4 1 1
4 1 2
4 1 3
4 1 4
4 1 5
4 2 1
4 2 2
4 2 3
4 2 4
4 2 5
4 3 1
4 3 2
4 3 3
4 3 4
4 3 5
4 4 1
4 4 2
4 4 3
4 4 4
4 4 5
4 5 1
4 5 2
4 5 3
4 5 4
4 5 5
5 1 1
5 1 2
5 1 3
5 1 4
5 1 5
5 2 1
5 2 2
5 2 3
5 2 4
5 2 5
5 3 1
5 3 2
5 3 3
5 3 4
5 3 5
5 4 1
5 4 2
5 4 3
5 4 4
5 4 5
5 5 1
5 5 2
5 5 3
5 5 4
5 5 5
At least in python (You should specify language if it's a constraint):
>>> from itertools import permutations as permu
>>> for i in permu(range(5), 3):
... print i
...
(0, 1, 2)
(0, 1, 3)
(0, 1, 4)
(0, 2, 1)
(0, 2, 3)
(0, 2, 4)
(0, 3, 1)
....
In recursive solution you don't have to sort the list every time. Giving sorted list to recursive function must be sifficient.
To do so, I've written this piece of C# code. Length of output result will be determined by len. Just remember that input length must be equal or bigger than len:
// Input must be sorted, Result must be initialized to empty list
void Iterate(List<int> input, int len, List<int> result)
{
if(result.Count == n)
print result
else
foreach (var i in input)
Iterate(input, len, result.Append(num).ToList())
}
Use this algorithm.
Input: X is the minimum number, Y is the maximum number, and Z is the number of independent choices.
Create an array of size Z, with each element equal to X. Call it Permutation.
Loop:
Add a copy of Permutation to the list of permutations.
Set J to Z minus 1.
Loop:
Add 1 to Permutation[J]. If Permutation[J] is now Y or less, break.
Set Permutation[J] to X.
Subtract 1 from J. If J is now less than 0, return the list of permutations.
Must be classic algorithm. But it always fun to write it from scratch. Here is Java class accepting data set and result list size parameters. Core method is generate(). Also lists might be copied on demand (to be more functional style).
import com.google.common.collect.Maps;
import org.apache.commons.lang.ArrayUtils;
import java.util.Map;
public class PermutationGenerator {
private int listValuesSize;
private int resultListSize;
private String[] currentList;
private Map<String, String> nextValue = Maps.newHashMap();
private int permutations = 0;
public PermutationGenerator(String[] dataSet, int resultListSize) {
this.listValuesSize = dataSet.length;
this.resultListSize = resultListSize;
init(dataSet);
}
private void init(String[] dataSet) {
// rolling values
String previous = dataSet[0];
for (int valuesIndex = 1; valuesIndex < dataSet.length; valuesIndex++) {
nextValue.put(previous, dataSet[valuesIndex]);
previous = dataSet[valuesIndex];
}
nextValue.put(dataSet[dataSet.length - 1], dataSet[0]);
// init
currentList = new String[resultListSize];
for (int i = 0; i < resultListSize; i++) {
currentList[i] = dataSet[0];
}
}
public void generate() {
generate(0, resultListSize - 1);
}
private void generate(int from, int to) {
if (from > to) {
return;
}
for (int i = 0; i < listValuesSize; i++) {
if (from == to) {
processList(currentList);
} else {
generate(from + 1, to);
}
roll(from);
}
}
private void roll(int position) {
currentList[position] = nextValue.get(currentList[position]);
}
private void processList(String[] list) {
permutations++;
System.out.println(ArrayUtils.toString(list));
}
public static void main(String... args) {
PermutationGenerator generator = new PermutationGenerator(new String[]{"1", "2", "3", "4", "5"}, 3);
generator.generate();
System.out.println(generator.permutations);
}
}