I am trying to create a function to identify whether or not a character is repeated in a given string.
int checkrow(char* row) {
int count, r;
for(int i = 0; i < strlen(row); i++) {
count = 1;
for(int j = i + 1; j < strlen(row); j++) {
if(row[i] == row[j]) {
count = count + 1;
}
}
if(count > 1 ) {
r = 0;
}
else {
r = 1;
}
}
return r;
}
This is my function at the moment, I am not getting an error or warning messages, but it is not identifying repeated characters.
I am very new to C and any help would be appreciated!
For each character you test, you set r to whether that character is repeated. So if the first character is repeated you set r = 0, but then if the second character is not repeated, you set r = 1.
You don't need to test every character. As soon you find a repeated character, you can return 0. If you get to the end of the loop, nothing was repeated, so you return 1.
int checkrow(char* row) {
for(size_t i = 0; i < strlen(row); i++) {
for(size_t j = i + 1; j < strlen(row); j++) {
if(row[i] == row[j]) {
return 0;
}
}
}
return 1;
}
Related
So I am writing code that will change the elements of an array and print out ONLY the numbers that come after a certain target. In this case the target is the number 4.
meaning that if my original array contains the numbers
5 6 4 3 2 1
the new array will only contain 3 2 1 because those are the numbers that come after the number 4.
I have this all in a method and so far my code prints out the number that comes after 4 but keeps printing that same number over and over and I don't know how to keep it printing the elements that follow
boolean four;
int location = 0;
four = contains(newArray, 4);
if (four == false) { // this returns the same array if there is no 4
return newArray;
} else {
for (int i = 0; i < newArray.length; i++) {
if (newArray[i] == 4) {
location = i;
}
}
for (int j = 0; j < newArray.length; j++) {
newArray[j] = newArray[location + 1];
}
return newArray;
}
You could also make use of the native implementation of System.arraycopy like this
for (int i = 0; i < arr.length; i++) {
if (arr[i] == 4) {
location = i;
break;
}
}
int[] out = new int[arr.length-location-1];
System.arraycopy(arr, location+1, out, 0, arr.length-location-1);
return out;
You should create a new array, since you can't change an array's length :
for (int i = 0; i < newArray.length; i++) {
if(newArray[i] == 4) {
location = i;
break;
}
}
int [] arr = new int[newArray.length - location - 1];
for(int j = 0; j < arr.length; j++) {
arr[j] = newArray[location+1+j];
}
newArray = arr;
I'm trying to track a player's location with x marking their spot. When the player enters a string I increment the coordinates accordingly. However when the player is located one space from the perimeter, then attempts to move to the edge of the map, the player disappears.
Example:
.....
...x.
.....
.....
.....
Player located at 'x'
If player enters string "right" and I move player_loc, array simply returns:
.....
.....
.....
.....
.....
I attempted to add a sort of buffer by increasing the size of the array. No luck. I've been stuck on this for almost a week now. Any help would be appreciated. I apologize for messy code. I'm a total newbie at this and I'm really just futzing around in the dark with all this stuff. I've researched this across the forums here and haven't found a solution. If you know of something that I possibly (probably) missed feel free to point me in that direction.
#include <stdio.h>
#include <string.h>
char map[6][6];
char player_loc = 'x';
int row;
int col;
void init_map()
{
for (int i = 0; i < 5; i++) {
for (int j = 0; j < 5; j++) {
map[i][j] = '.';
}
}
}
void print_map()
{
for (int i = 0; i < 5; i++) {
for (int j = 0; j < 5; j++) {
printf("%c", map[i][j]);
}
printf("\n");
}
}
int get_player_loc()
{
for (int j = 0; j < 5; j++) {
for (int k = 0; k < 5; k++) {
if(map[j][k] == player_loc)
{
row = k;
col = j;
}
}
}
return row;
return col;
}
void init_player_loc()
{
int check = 1;
for (int g = 0; g < 5; g++) {
for (int h = 0; h < 5; h++) {
if (map[g][h] == 'x') {
check = 0;
}
}
}
if(check == 1) {
map[0][0] = player_loc;
} else {
get_player_loc();
}
}
void move_left()
{
for (int i = 0; i < 5; i++) {
for (int j = 0; j < 5; j++) {
if (map[i][j] == player_loc) {
map[i][j-1] = player_loc;
map[i][j] = '.';
}
}
}
}
void move_right()
{
for (int i = 0; i < 5; i++) {
for (int j = 0; j < 5; j++) {
if (map[i][j] == player_loc) {
map[i][j+1] = player_loc;
map[i][j] = '.';
}
}
}
}
int main(int argc, char* argv[])
{
char input[15];
printf("You enter a room...you can go left, right, or straight. Which way do you go?\n");
int done = 0;
init_map();
map[3][3] = player_loc;
//init_player_loc();
print_map();
while (!done) {
scanf("%s", input);
if (strcmp("left", input) == 0) {
move_left();
printf("You go left...\n");
print_map();
get_player_loc();
printf("%d %d\n", row, col);
done = 1;
}
else if (strcmp("right", input) == 0) {
move_right();
printf("You go right...\n");
print_map();
get_player_loc();
printf("%d %d\n", row, col);
done = 1;
}
else if (strcmp("straight", input) == 0) {
printf("You go straight...");
done = 1;
}
else {
printf("Sorry, can't do that.\n");
}
}
}
You must break the loop if you find the player location, e.g
void move_right()
{
for (int i = 0; i < 5; i++) {
for (int j = 0; j < 5; j++) {
if (map[i][j] == player_loc) {
map[i][j+1] = player_loc;
map[i][j] = '.';
return;
}
}
}
}
In your code you move right the player, and the next loop will find the player in the new location and do the right move again, forever.
Moreover in your code you are not taking care of boundaries of your 2d matrix: j+1 is valid only if j<5.
Then a better code should be
void move_right()
{
for (int i = 0; i < 4; i++) {
for (int j = 0; j < 4; j++) {
if (map[i][j] == player_loc) {
map[i][j+1] = player_loc;
map[i][j] = '.';
return;
}
}
}
}
The problem is that your move_right function picks up the player and moves them completely off of the map. Let's say your player is at [0, 2] and step through the code.
for (int j = 0; j < 5; j++) {
if (map[i][j] == player_loc) {
map[i][j+1] = player_loc;
map[i][j] = '.';
}
}
[0, 0] No player here, move along
[0, 1] No player here, move along
[0, 2] Found a player! Move them right to [0, 3]
[0, 3] Found a player! Move them right to [0, 4]
[0, 4] Found a player! Move them right to [0, 5]
At 5, the loop ends. Because of the buffer you added, your array is 6x6, so the player is stashed in the wings without crashing the program. There are a few things you should do:
Once you've found and moved the player, break or return so they'll only move once.
Make your array 5x5 (or print all 6x6) so you can see everything.
Do some bounds checking so the player isn't allowed to move right from j = 5.
Watch out for this same bug in move_up, where it would happen as you increment i.
Your loops allow for checking the position twice, once at i,j, and again at i,(j+1) (or some other variant). This probably isn't what you intend. After you find the player you should make the updates and then break out of the loops.
Also, the code as is allows for indexing passed the bounds of the array, in theory. Also not what is desired. You may consider bounds checking. I don't know what is supposed to happen when the player moves right and there is a wall to the right. Does he not move? Wrap around? LR corner could cause seg fault as it is now.
You appear to have row and column indeces transposed in the get_player_loc function, as well as having two return statements (the compiler should warn you about unreachable code), neither of which is required or used by the calling code.
At the start, initialise the row and col variables. (Values taken from your main.)
int row = 3;
int col = 3;
Change the get_player_loc function so that it just updates the globals row and col. It sets row and col to 0 if the player is not found, as per the original.
void get_player_loc(void)
{
for (int j = 0; j < 5; j++) {
for (int k = 0; k < 5; k++) {
if(map[j][k] == player_loc)
{
// The meaning of row and col is set by how they are used
// to index the array in the move and print functions. Keep
// the same order and meaning here.
row = j;
col = k;
return;
}
}
}
// Set row and col to 0 if the location is not found.
row = 0;
col = 0;
map[0][0] = player_loc;
}
You'll still have problems when they reach an edge, due to the index into the array going out of bounds in the move functions, but that's a different problem.
So I have an array board[][] whose values keep shuffling around. It is a square array with dimensions d*d. I want to check the array to see if all of its values are in ascending order.
for (int i = 0; i < d; i++)
{
for (int j = 0; i < d; i++)
{
if (board[i][j] == (d * i) + j + 1)
{
return true;
}
else
{
return false;
}
}
}
the problem is that as soon as the first element in the array board[0][0] = 1, it returns true, and ends my code. I don't know how to implement it so that it doesn't return true until all the elements in the array are in ascending order, from 1 to (d*d - 1).
Thank you!
If I understood your question correctly I think you want to do this:
int Previous = board[0][0];
for (int i = 0; i < d; i++)
{
for (int j = 0; j < d; j++)
{
if (board[i][j] < Previous)
{
return false;
}
Previous = board[i][j];
}
}
return true; // Only at the end do we know that all elements are in ascending order
Problems with what you have are:
You are returning on either condition instead of returning after all values have been checked
Your second for loop is wrong and references i, not j
Your comparison is comparing board values against the indexes, not other board values
This should work
for (int i = 0; i < d; i++)
{
for (int j = 0; j < d; j++)
{
if (board[i][j] != (d * i) + j + 1)
{
return false;
}
}
}
return true;
Try replacing return true with continue:
for (int i = 0; i < d; i++)
{
for (int j = 0; i < d; i++)
{
if (board[i][j] == (d * i) + j + 1)
{
continue;
}
else
{
return false;
}
}
}
You can also remove the continue clause completely if you reverse the condition:
if (board[i][j] != (d * i) + j + 1)
{
return false;
}
1) First what you mean by ascending order (vertically, horizontally or in diagonal ?)
2) Replace your if statement
if ((board[i][j] > board[i][j+1]) || (board[i][j] > board[i+1][j]))
It crashes with a debug error and says stack around variable 'code' was corrupted. This is code for a hamming code lab I am doing. The input file is just a bunch of 1's and 0's on the same line. Why is it crashing?
void processFile(FILE* read, char* InMessage) {
int i = 0, count = 0;
for (i = 0; !feof(read); i++) {
InMessage[i] = fgetc(read);
count++;
}
InMessage[count] = '\0';
}
void hammingCode(char* InMessage) {
int len = strlen(InMessage), i = 0, j = 0;
char code[12], temp[1000];
temp[0] = '\0';
for (i = 0, j = 0; i < len; i++, j++) {
code[j] = InMessage[i];
if (j == 10) {
j = 0;
decode(code);
code[11] = '\0';
strcat_s(temp, sizeof(char)*1000, code);
}
}
strcpy_s(InMessage, sizeof(char)*1000, temp);
}
void decode(char* codeWord) {
int i = 0, j = 0, parity[4] = {0}, diffParity[4] = {0}, twoPower = 0, readNSkip = 0, bitSum = 0;
for (i = 0; i < 4; i++) {
twoPower = (int)pow((double)2, i);
for (j = twoPower; j <= 12; j++) {
if (readNSkip <= twoPower) {
if (j != twoPower) {
parity[i] += codeWord[j-2] - 48;
}
readNSkip++;
}
else {
if (readNSkip == twoPower*2)
readNSkip = 0;
readNSkip++;
}
}
if (parity[i] % 2 == 0)
parity[i] = 0;
else
parity[i] = 1;
if ((codeWord[twoPower-1] - 48) != parity[i])
diffParity[i] = 1;
}
for (i = 0; i < 4; i++) {
twoPower = (int)pow((double)2, i);
bitSum += diffParity[i]*twoPower;
}
codeWord[bitSum] = !codeWord[bitSum];
}
There's two problems I see here:
It looks to me like you are calculating the size of the InMessage buffer incorrectly in your hammingCode function:
int len = strlen(InMessage), i = 0, j = 0;
The strlen function determines the length of the string by finding the position of the first null terminator. If InMessage is not cleared, then this could give you some strange lengths as it will contain a random sequence of bytes. Conversely, if you have cleared the buffer then len will be 0.
To overcome this problem, it is better for the caller to provide the size of the buffer:
int hammingCode (char *InMessage, size_t messageSize)
And use messageSize in place of len.
It's advisable to use this same strategy for your other two functions as well as currently there is a chance of overflowing the provided buffers.
Following on from the previous problem, it may be that the decode function is writing outside the bounds of the buffer. Providing the length of the buffer to decode and adding the appropriate checks to ensure the function does not write outside the given bounds would be a good idea.
For my java class one of the exercises is to print out a diamond using nested for loops. In the exercise you need to use the minimum amount of outputs, while using nested for loops. The other stipulation is that each output can only output 1 character such as a single space, a single asterisk, or a single end line statement.
I've finished it but i was wondering if there was an easier way to do it, or if anyone has tips on cleaning up my code. It just seems like ended up writing way more than was needed. Any help and tips are greatly appreciated. :)
Here is what the end result needs to look like:
Here is my code:
public class Diamond
{
public static void main(String args[])
{
int b = 11; // secondary asterisk loop counter
int ac = 2; // asterisk count
int sc = 5; // space count
int elc = 2; // end line count
int slc = 1; // space loop count
int sslc = 1; // secondary space loop count
for(int e = 1; e < elc && elc < 12;e++)
{
if(elc <= 6)
{
for(int a = 1; a < ac; a++)
{
for(;sc <= 5 && sc > 0; sc--)
{
System.out.print(" ");
}
System.out.print("*");
}
ac += 2;
sc = 5 - slc;
slc += 1;
}
else if (elc > 6)
{
ac -= 2;
sc = 1;
for (; b < ac ; b++)
{
for(;sc <= sslc && sc > -2; sc++)
{
System.out.print(" ");
}
System.out.print("*");
}
b = 1;
sslc += 1;
}
if(elc != 6)
{
System.out.println();
}
elc += 1;
}
}
}
You may try writing down the 4 edges of the diamond as equations (x+y=4; x-y=2... for example). Then just make a nested loop through each of the cell in the grid to see if you should print a space or a star. The test would look like
If f1(x,y) or f2(x,y) or f3(x,y) or f4(x,y): print '*' else print ' '
where f1,f2,f3,f4 are the equations for the 4 diagonals.
If you are required to minimize the number of characters to be printed, either use an array to prepare, then ignore the trailing spaces; or use some ad-hoc rule (like every row only 2 stars except the 1st and last...)
public class ASultan
{
public static void main(String[] args) {
int size = 9;
for (int i = 1; i < size; i += 2) {
for (int k = size; k >= i; k -= 2) {
System.out.print(" ");
}
for (int j = 1; j <= i; j++) {
System.out.print("*");
}
System.out.println();
}
for (int i = 1; i <= size; i += 2) {
for (int k = 1; k <= i; k += 2) {
System.out.print(" ");
}
for (int j = size; j >= i; j--) {
System.out.print("*");
}
System.out.println();
}
}
}