Java filling char matrix from user without space [duplicate] - for-loop

This question already exists:
Java matrix ask user to input values [duplicate]
Closed 5 months ago.
I want to be able to ask the user to fill the matrix. The code works but the problem is that if the user dont enter values with space the output will be wrong.
enter code here
char [][] matrix = new char[2][2];
Scanner scanner = new Scanner(System.in);
for (int i = 0; i < 2; i++) {
for (int j = 0; j < 2; j++) {
matrix[i][j] =scanner.next().charAt(0);
}
};
// the user can enter with space:
a b
c d
// however when the user enters without space the program dont stop and the matrix dont get filled in the right way:
ab
cd
// expected output should fill out the matrix with given values from the user without space.

It requires a space with this code because the default delimiter of Scanner is whitespace. Meaning that Scanner splits up the input at whitespace (like spaces) and scanner.next() returns the next chunk. In order to not require spaces, you have to override the default delimiter using
scanner.useDelimiter("");
before you call scanner.next() (i.e. before the for loops).

Related

Why does for loop quit after calling another method?

I am trying to fill a matrix with data read from a text file. The matrix is simply a 2D array that has already been created with parameters. I have check and the array is being created to the correct size based on parameters. For some reason when I scan the next value (value) and then try to insert it at a certain point in the array it is successful once and then quits without filling the rest of the array. If the insertAt method is removed than the loops work perfectly going through all the needed cells. For some reason when the method is added and called it works fine for the first cell but then quits after that.
While loop that inserts the value at a specific point.
while(scan.hasNext()) {
for(int i = 0; i < m1.row; i++) {
for(int j = 0; j < m1.column; j++) {
value = scan.nextInt();
m1.insertAt(i, j, value);
}
}
}
Method for matrix that control the insertion of the value.
public void insertAt(int row, int column, int value) {
if(row >= 0 && column >= 0) {
matrix[row][column] = value;
} else {
System.out.println("Error inserting value. Row: " + row + " Column: " + column);
}
}
Discovered it does this because you cannot put a variable in at a specific point at one time, even if you try to put them in in order. If the matrix is initialized and filled with 0's or some other digit it works fine. It has to be filled creating an empty matrix with a specific size does not work. Otherwise you have to restart the entire method each time to add 1 variable.

Input multiple strings with spaces in c++ in 2d char array

For a given integer n at runtime, I have to input n strings which can have spaces in between them.
The test case format for input is:
3
xyz b
abcd
defg
So I am taking input like this because cin skips spaces.
int n, column = 1000;// maximum size of strings=1000
cin >> n;
char **String = 0;
String = new char *[n];
int i;
for (i=0; i < n; i++){
String[i] = new char [column];
}
for (i = 0; i < n; i++)
cin.getline(String[i],1000)
}
After the 2nd string i.e. "abcd" its taking a newline as the 3rd string. Why is that?
If this is wrong, how do I take input in this case?
Your code is correct. The problem lies just in the way the input is given at terminal.
Suppose I execute the program, and I put n = 2, i.e. I wish to input two strings. If after typing 2, I press enter, the first string that goes into Strings is an empty one. But, if I type the string, that I intend to input first, just after the 2 (no space after 2), then my problem is solved.
What if I don't want to change the way I wish to input (i.e. I wish to press enter after entering the number of strings that I want to input, and then take the upcoming strings in), then what I can do is, write cin.getline(String[0], 1000) before the following loop in the above code.
for (i = 0; i < n; i++)
cin.getline(String[i],1000)
For once we take the empty space after 2 (2, being the input n, referring to the details above in this answer) as the first input string in String, but the loop that follows starts taking input afresh, and the input string that follows on terminal at the next line (the first one we actually intend to input), is saved in String[0].
So, the problem is solved then.

Displaying a triangle pattern in with nested loops

The problem I am having is displaying a triangle pattern with nested loops. More specifically an upside down one. I am currently having difficulty displaying the left side of the triangle. I can see the problem to an extent but I am having trouble trying to fix it. I think the problem is I cant get the number of symbols per line to display correctly in the 2nd for loop statement without having too many numbers being displayed. Here is my code.
public class DisplayPatternC {
public static void main(String[] args) {
int rows = 7;
int noOfSpaces = 0;
for (int i = 1; i <= rows; i++) {
for (int j = 7; i <= j; j--) {
System.out.print(i);
}
System.out.println();
}
}
}
Here is my output:
1111111
222222
33333
4444
555
66
7
The output I want is:
1111111111111
22222222222
333333333
4444444
55555
666
7
Well, just by observing the output you can determine that the number of digits per row is: (starting from the bottom) 1,3,5,7,9... Which is a formula of 2n - 1. And you'll need to output spaces accordingly if you wish to make the triangle as specified, which goes in the pattern 0,1,2,3,4...
So the formula to obtain number of digits for each $i is 2 * ($rows - $i + 1) - 1. And the number of spaces before the start of printing the digits is $i - 1. So go figure :)

Using a for loop to create a pattern output and how to change the formula to change the pattern

I have to work out how to change code so that the output in the columns or rows I have changes. I have done the following for one that is supposed to print 5 by 5 rows of asterisks with the third row having plus signs instead. It is almost right but something is making the plus signs happen on the 4th row instead of the third. My lecturer said something about it in class being to do with when the value is grabbed, but I can't remember what and it's the weekend so I can't ask him.
I have read a few questions and that gave me a jumping point but I'm still unclear on the following things;
Can you please tell me where I'm going wrong with the third line and fourth line being opposite to how I would like them and give me any pointers on how to change things in specific rows or columns?
Thanks, here is my code;
public class OutputB
{
public static void main(String[] args)
{
int rows = 5; // tells the program how many rows
int cols = 5; // tells the program how many columns
for (int r = 0; r < rows; r++)
{
for (int c = 0; c < cols; c++)
if(r != 3)
{
System.out.print("*");
}
else
{
System.out.print("+");
}
System.out.println();
You're starting at zero, which means the third increment is actually the fourth. You have two options to fix this. You can either subtract 1 from the desired row number...
int rows = 5; // tells the program how many rows
int cols = 5; // tells the program how many columns
int rowOfThePlusSymbol = 3;
...
if(r != rowOfThePlusSymbol-1)
...or you you can start at 1 in your for loop. If you do so, be sure to put <= in your for loop also, so you loop the desired number of times.
...
for (int r = 1; r <= rows; r++)
{
for (int c = 1; c <= cols; c++)
...
}
I don't encourage using the latter solution because it is normal practice to start at zero when using increments or indexes of lists.

How can we find a repeated number in array in O(n) time and O(1) space complexity

How can we find a repeated number in array in O(n) time and O(1) complexity?
eg
array 2,1,4,3,3,10
output is 3
EDIT:
I tried in following way.
i found that if no is oddly repeated then we can achieve the result by doing xor . so i thought to make the element which is odd no repeating to even no and every evenly repeating no to odd.but for that i need to find out unique element array from input array in O(n) but couldn't find the way.
Assuming that there is an upped bound for the values of the numbers in the array (which is the case with all built-in integer types in all programming languages I 've ever used -- for example, let's say they are 32-bit integers) there is a solution that uses constant space:
Create an array of N elements, where N is the upper bound for the integer values in the input array and initialize all elements to 0 or false or some equivalent. I 'll call this the lookup array.
Loop over the input array, and use each number to index into the lookup array. If the value you find is 1 or true (etc), the current number in the input array is a duplicate.
Otherwise, set the corresponding value in the lookup array to 1 or true to remember that we have seen this particular input number.
Technically, this is O(n) time and O(1) space, and it does not destroy the input array. Practically, you would need things to be going your way to have such a program actually run (e.g. it's out of the question if talking about 64-bit integers in the input).
Without knowing more about the possible values in the array you can't.
With O(1) space requirement the fastest way is to sort the array so it's going to be at least O(n*log(n)).
Use Bit manipulation ... traverse the list in one loop.
Check if the mask is 1 by shifting the value from i.
If so print out repeated value i.
If the value is unset, set it.
*If you only want to show one repeated values once, add another integer show and set its bits as well like in the example below.
**This is in java, I'm not sure we will reach it, but you might want to also add a check using Integer.MAX_VALUE.
public static void repeated( int[] vals ) {
int mask = 0;
int show = 0;
for( int i : vals ) {
// get bit in mask
if( (( mask >> i ) & 1) == 1 &&
(( show >> i ) & 1) == 0 )
{
System.out.println( "\n\tfound: " + i );
show = show | (1 << i);
}
// set mask if not found
else
{
mask = mask | (1 << i);
System.out.println( "new: " + i );
}
System.out.println( "mask: " + mask );
}
}
This is impossible without knowing any restricted rules about the input array, either that the Memory complexity would have some dependency on the input size or that the time complexity is gonna be higher.
The 2 answers above are infact the best answers for getting near what you have asked, one's trade off is Time where the second trade off is in Memory, but you cant have it run in O(n) time and O(1) complexity in SOME UNKNOWN INPUT ARRAY.
I met the problem too and my solution is using hashMap .The python version is the following:
def findRepeatNumber(lists):
hashMap = {}
for i in xrange(len(lists)):
if lists[i] in hashMap:
return lists[i]
else:
hashMap[lists[i]]=i+1
return
It is possible only if you have a specific data. Eg all numbers are of a small range. Then you could store repeat info in the source array not affecting the whole scanning and analyzing process.
Simplified example: You know that all the numbers are smaller than 100, then you can mark repeat count for a number using extra zeroes, like put 900 instead of 9 when 9 is occurred twice.
It is easy when NumMax-NumMin
http://www.geeksforgeeks.org/find-the-maximum-repeating-number-in-ok-time/
public static string RepeatedNumber()
{
int[] input = {66, 23, 34, 0, 5, 4};
int[] indexer = {0,0,0,0,0,0}
var found = 0;
for (int i = 0; i < input.Length; i++)
{
var toFind = input[i];
for (int j = 0; j < input.Length; j++)
{
if (input[j] == toFind && (indexer[j] == 1))
{
found = input[j];
}
else if (input[j] == toFind)
{
indexer[j] = 1;
}
}
}
return $"most repeated item in the array is {found}";
}
You can do this
#include<iostream.h>
#include<conio.h>
#include<stdio.h>
void main ()
{
clrscr();
int array[5],rep=0;
for(int i=1; i<=5; i++)
{
cout<<"enter elements"<<endl;
cin>>array[i];
}
for(i=1; i<=5; i++)
{
if(array[i]==array[i+1])
{
rep=array[i];
}
}
cout<<" repeat value is"<<rep;
getch();
}

Resources