Liczba miejsc w napisie, w których jakiś znak występuje obok siebie wiele razy.

0

Jak napisać taką funkcję jak w temacie? Udało mi się stworzyć coś takiego, ale nie działa dla wszystkich przypadków.

#include <iostream>

using namespace std;

int dlugosc (char* s)
{
    int i;
    for (i=0; s[i]; i++);
    return i;
}

int p(char* s)
{
    int p=0;
    for (int j=0; j<dlugosc(s)-1; j++)
    {
    if (s[j+1]==s[j])    
    for (int i=0; i<dlugosc(s)-2; i+=2)
    {
        if (s[i+1]==s[i] && (s[i+2]==s[i] || s[i+2]!=s[i]))
        p++;
    } return p;
}}

0

A co to: s[i+2]==s[i] || s[i+2]!=s[i] ma być?

0

@lion137: W taki sposób próbowałam zapisać, że dwa znaki, które będą równe, będą wskazywać na wielokrotne wystąpienie, ale również kiedy będzie ich więcej

1

Trzeba przesuwać się po stringu, aż znaki nie będą równe:

    int p=0, i = 0;
    for (int j=0; j<dlugosc(s)-1; j++)
    {
      if (s[j] == s[j+1]) {
        i = j;
        while (s[i+1]==s[i])     
        {
          i++;
          j++;
        }
        p++;
      }
    }
    return p;
0

@lion137: Bardzo dziękuję za pomoc!

2

A może by tak bardziej ceplusplusowo :P

template<typename T>
int count_adjacent(T const& container)
{
   int result = 0; 
    auto it = adjacent_find(begin(container), end(container));
    while (it != end(container)) {
        ++result;
        it = adjacent_find(it + count(it, end(container), *it), end(container));
    }
    return result;
}
0

A może tak bardziej jednolinijkowo:

#include <iostream>
#include <sstream>
using namespace std;

size_t countRepeat(istream &sin)
{
	size_t result=0,repeat=0;
	for(int prev=EOF,ch=0;sin;prev=ch) if((ch=sin.get())==prev) ++repeat; else if(repeat>0) result+=!(repeat=0);
	return result;
}

int main()
{
	stringstream ss("Ala mmaa kotaa");
	cout<<countRepeat(ss);
    return 0;
}
0

Ponieważ miało być z char *:

#include <stdio.h>

int countRepeats(char *cptr) {
  char prior = *cptr;
  int clen = 0;
  int result = 0;
  
  while(*cptr) {
    cptr++;
    if (*cptr == prior)	{
    	result += !clen;
    	clen++;
    } else {
    	prior = *cptr;
    	clen = 0;
    }
  }
  
  return result;
}

void test(int testId, char *text, int expected) {
	int actual = countRepeats(text);
	if (actual == expected) {
		printf("Test %d OK\n", testId);
	} else {
		printf("Test %d failed, expected: %d, actual: %d\n", testId, expected, actual);
	}
}

int main(void) {
	
	test(1, "Too jeesttt ttest...", 5);
	test(2, "", 0);
	test(3, "A", 0);
	test(4, "AA", 1);
	test(5, "AAA", 1);
	test(6, "AA A", 1);
	test(7, "AA AA", 2);
	test(8, " AA", 1);
	test(9, "AA ", 1);
	test(10, " AA ", 1);
	test(11, " A A ", 0);
	test(12, "DDBCDCCCCBB", 3);
	
	return 0;
}

https://ideone.com/20Ny2J

1 użytkowników online, w tym zalogowanych: 0, gości: 1