Binary Search Excercise - c

I'm doing an exercise in C, but I don't know why as first result I have always -1 (that is impossible).
I have -1 only after the swap to ordinate the array.
#include <stdio.h>
#include <time.h>
#include <stdlib.h>
main(){
int vet[100], cont[100];
int i, c, f=100;
int swap;
int r=0;
int search;
srand(time(NULL));
for(i=0;i<100;i++){
vet[i]=rand()%100+1;
}
while(r==0){
r=1;
for(i=0;i<100;i++){
if(vet[i]>vet[i+1]){
swap=vet[i+1];
vet[i+1]=vet[i];
vet[i]=swap;
r=0;
}
}
}
for(i=0;i<100;i++){
printf("%d) %d\n", i+1, vet[i]);
}
i=0;
r=0;
printf("Inserisci numero da ricercare (1-10000) -> ");
scanf("%d", &search);
if(search>10000 || search<0){
printf("Hai inserito un valore non valido\n");
}
else{
c=(i+f)/2;
while(vet[c]!=search && i<f){
if(vet[c]<search){
i=c+1;
c=(i+f)/2;
}
else if(vet[c]>search){
f=c-1;
c=(i+f)/2;
}
if(vet[c]==search){
cont[r]=c+1;
r++;
}
}
if(vet[c]!=search){
printf("Non e\' stato trovato nessun valore %d", searchâ—†
}
else{
for(i=0;i<r;i++){
printf("%d\n", cont[i]);
}
}
}
}
Now I must use srand(time(NULL)) I know that there are better solutions.
The exercise isn't complete, now I' m trying to solve this error, someone can help me?
EDIT:
I'm using OPENVMS to compile, link and run

Your problem is probably here:
for(i=0;i<100;i++){
if(vet[i]>vet[i+1]){
When i=99, and you access vet[i+1], you are off the end of the array. This element is not defined, and it's probably just fluke that you don't get any worse behaviour.
EDIT:
So the solution is to change in
for(i=0;i<99;i++){
if(vet[i]>vet[i+1]){

Related

I Want to add the numbers in the matrix

I want the sum of the numbers in the matrix in each column to add up, tried doing this using different variation's of the same music[i+1][j]+=music[i][j], but its not working, so basically what the program does, it assigns 3 points to the first number the user inputs as his favorite song, the second song get 2 points and the third 1 point, i want the matrix at the end to sum up all the points from the participants and give me the total.
#include <stdio.h>
#include <stdlib.h>
int main()
{ int num=0, pers=0;
int i,j, k;
int votos=0;
printf("Digite la cantidad de personas:");
scanf("%d", &pers);
float music[pers+1][10];
for(i=0;i<pers+1;i++){
for(j=0;j<10;j++){
music[i][j]=0;
}
}
for(i=0;i<pers;i++){
printf("Participante %d :\n",i+1);
for(k=1;k<=3;k++){
printf("Digite el numero de sus 3 canciones favoritas %d:\n",k);
scanf("%d",&num);
for(j=0;j<9;j++){
if (k==1){
music[i][num-1]=3;
}
if (k==2){
music[i][num-1]=2;
}
if (k==3){
music[i][num-1]=1;
}
music[10][j]+=music[i][j];
}
}
}
for(i=0;i<pers+1;i++){
for(j=0;j<10;j++){
printf("%.2f\t",music[i][j]);
}
printf("\n");
}
return 0;
}
GDB is your friend for these sorts of problems. You can install an interactive debugger and step through your code line by line to see what values your matrix takes on certain input.
If you did that, you may have saw that you're accessing the 10th row of your matrix. Even if pers is initialized to three.
There's also an issue where you begin summing music values as they're being initialized (leading to over counting).
for (i = 0; i < pers; i++)
{
printf("Participante %d :\n", i + 1);
for (k = 1; k <= 3; k++)
{
printf("Digite el numero de sus 3 canciones favoritas %d:\n", k);
scanf("%d", &num);
if (k == 1)
{
music[i][num - 1] = 3;
}
if (k == 2)
{
music[i][num - 1] = 2;
}
if (k == 3)
{
music[i][num - 1] = 1;
}
}
}
for(j = 0 ; j < 10; j++)
{
for (i = 0; i < pers+1; i++)
music[pers][j] += music[i][j];
}
I'm hoping this code doesn't fully solve your problem since it'll be good for you to look into gdb and learn how to interact with your code and understand where its deviating from your expectations.
It'll also help to do as paddy suggested and explain what your input and output is supposed to look like.
Try This Code It working and sum up
#include <stdio.h>
#include <stdlib.h>
int main(){
int num=0, pers=0;
int i,j, k;
int votos=0;
printf("Digite la cantidad de personas:");
scanf("%d", &pers);
float music[100][100];
float sum[100][100];
for(i=0;i<pers+1;i++){
for(j=0;j<10;j++){
music[i][j]=0;
}
}
for(i=0;i<pers;i++){
printf("Participante %d :\n",i+1);
for(k=1;k<=3;k++){
printf("Digite el numero de sus 3 canciones favoritas %d:\n",k);
scanf("%d",&num);
for(j=0;j<9;j++){
if (k==1){
music[i][num-1]=3;
}
if (k==2){
music[i][num-1]=2;
}
if (k==3){
music[i][num-1]=1;
}
sum[i][j]+=music[i][j];
}
}
}
for(i=0;i<pers+1;i++){
for(j=0;j<10;j++){
printf("%.2f\t",sum[i][j]);
}
printf("\n");
}
return 0;
}

C prints other integer number than what it shows on Watches. Why is that?

I tried adding watches and debugging it step by step,and although it works correctly on watches,it doesn't print the right value. What could be the reason for this outcome?
I'm a newbie, thanks in advance.
#include <stdio.h>
#include <stdlib.h>
int main()
{
int n,pal,nr;
printf("Introd un numar : ");
scanf("%d",&nr);
n= nr;
pal=0;
while(n!=0) {
pal=pal*10+n%10;
n=(int)n/10;
}
if (pal==nr)
printf("%d este palindrom ",&pal);
else
printf("%d nu este palindrom ",&pal);
return 0;
}
Change your printf calls like below:
if (pal==nr)
printf("%d este palindrom ",pal);
else
printf("%d nu este palindrom ",pal);

Mastermind - checking numbers (or colors) in the wrong place (C)

I trying to code mastermind with numbers, 1-6, and I can't do the part where it says how many numbers are in the wrong position. Sometimes it works well, but there are some occasions where it bugs.
Here's an example, if the random number is {5, 2, 3, 3} and the input is {5, 3, 2, 2}, instead of saying "1 right position, 2 wrong position" it says "1 right position, 3 wrong position". Not sure how to fix what I wrote.
for(j=0;j<4;j++){ //rp=rightPlace; wp=wrongPlace; c=code(random); in=input
if(c[j]==in[j])rp++;
}
for(j=0;j<4;j++){
for(i=0;i<4;i++){
if(c[j]==in[i]){wp++;break;}
}
}wp-=rp;
On most occasions it works out, but in this one it doesn't. I also understand why it doesn't work, but I can't even think of a way to fix it on paper.
Maybe getting another variable to avoid comparing the same place that was already compared if it has the same value? (in this case it wouldn't compare the second 3 of the code with the only 3 of the input)
almost full code, took the random out
#include <stdio.h>
#include <time.h>
#include <stdlib.h>
int main (void){
int c[4],in[4],i,j,ct=0,r,w=0,rp=0,wp=0;
srand(time(NULL));
c[0]=5;
c[1]=2;
c[2]=3;
c[3]=3;
for (i=0;i<4;i++){
printf("%d ",c[i]);
}printf("\n");
do{
ct++;
printf("Try? ");
scanf("%d %d %d %d",&in[0],&in[1],&in[2],&in[3]);
for(j=0;j<4;j++){
if(c[j]==in[j])rp++;
}
for(j=0;j<4;j++){
for(i=0;i<4;i++){
if(c[i]==in[j]){wp++;break;}
}
}
wp-=rp;
printf("Right places: %d\nWrong places: %d\n",sc,se);
if (rp==4){w=1; break;}
wp=0;rp=0;
}while(w==0);
printf("Code found in %d attempt(s)!\n",ct);
return 0;
}
full working code (portuguese comments and initials)
#include <stdio.h>
#include <time.h>
#include <stdlib.h>
int main (void){
int c[4],in[4],i,j,ct=0,sc=0,se=0;
srand(time(NULL));
//numeros aleatorios de 1 a 6
for(i=0;i<4;i++){
c[i]=rand()%6+1;
}
do{
ct++;
printf("Tentativa: ");
scanf("%d %d %d %d",&in[0],&in[1],&in[2],&in[3]);
//quantos no sitio certo
for(j=0;j<4;j++){
if(c[j]==in[j])sc++;
}//quantos que existem repetidos independentemente do sitio
for(j=0;j<4;j++){
for(i=0;i<4;i++){
if(c[j]==in[i]){se++;in[i]=0;break;}//podemos alterar o valor do input para 0 porque e alterado repetidamente e nao tem um valor fixo
}
}
se-=sc; //a diferenca destes diz quantos certos estao no sitio errado
printf("Sitio certo: %d\nSitio errado: %d\n",sc,se);
if (sc==4) break;
se=0;sc=0;//repor
}while(0==0);//existe break, nao vale apena criar mais variaveis
printf("Descoberto em %d tentativa(s)!\n",ct);
return 0;
}
The problem is this part:
for(j=0;j<4;j++){
for(i=0;i<4;i++){
if(c[j]==in[i]){wp++;break;} // problem here
}
}
with your given inputs, both of the '3' input values generate wrong place increments, because there is a 3 in the solution. As already mentioned, you have to "remove" a 3 from the solution (or account that it has already been checked) once you determine a "right color wrong place" status.

making a staircase of x's using loops in C, but I keep getting squares

So I need to make a staircase but I clearly have something wrong with my logic. Any advice on how to approach this? I only end up getting squares.
#include <stdio.h>
int main()
{
int a,b,z,y,p;
char x;
scanf("%i ", &a);
printf("Number of stairs is: %i\n", a);
printf("up: \n");
for(b=0; b<a; b++) {
for(z=1; a>=z; z++) {
x='x';
p=1;
if ((p=z)) {
printf("%c", x);
}
else {
printf(" ");
}
p++;
}
printf("\n");
}
}
Your code has many flaws and lack of clarity is one of them. Nevertheless, the reason you have a square is because p=z is always true (setting the value of p to z returns the value of z and this, in your code is always 1 or higher - a true value for C standards).
Here is a code that works, loosely based on your example:
#include <stdio.h>
int main() {
int numberSteps,currentStep,currentColumn;
scanf("%i", &numberSteps);
printf("Number of stairs is: %i\n", numberSteps);
printf("up: \n");
for(currentStep=0; currentStep<numberSteps; currentStep++) {
for(currentColumn=0; currentStep>=currentColumn; currentColumn++) {
printf("x");
}
printf("\n");
}
}
Please notice that I changed the variable names so that they became meaningful and also got rid of the unnecessary variables and the unnecessary test if ((p=z)) that was cluttering your code.

c program to find the least number of swaps to arrange an 3x3 array of 1-9 in ascending order under conditions on swaps

PS- i don't have a lot of programming experience, i am new to all this. so please help me solve this problem which i got as a project in college.
conditions of the game : you may swap two adjacent tiles if their sum is a prime number. Two tiles are considered adjacent if they have a common edge.
this is a problem from
http://www.codechef.com/problems/H1
though solutions are available there, but i am not able to understand them.
i have been working on this for a long this but i am not able to solve this.
the first program i made swaps any two tiles (which follow conditions) randomly. this way it calculates the swaps. for easy problems, it will most probably find the least number of counts. but for complex ones it hardly does. it is not at all efficient.
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int a[]={1,3,2,4,5,6,7,8,9};
int b[]={1,2,3,4,5,6,7,8,9};
int c[9];
int count=0;
void swap(){
int p,q,tmp;
for(p=0;p<9;p++){
for(q=p+1;q<9;q++){
if(prime(a[p],a[q])&&position(p,q)){
if(a[p]>a[q]){
tmp=a[p];
a[p]=a[q];
a[q]=tmp;
count++;
}
}
}
}
printf("\n\nswapstart\n\n");
for(p=0;p<9;p++){
printf("%d ", a[p]);
}
printf("\n\nswapover\n\n");
}
int prime(int a, int b){
int c=a+b;
if(c==3||c==5||c==7||c==11||c==13||c==17){
return 1;
}
return 0;
}
int position(int a, int b){
if((a-b==1||b-a==1||a-b==3||b-a==3) && (!((a==2&&b==3)||(a==3&&b==2)||(a==5&&b==6)||(a==6&&b==5))))
return 1;
else
return 0;
}
int main()
{
int i,j,temp,cnd=0,m,times=1000,finalcount=10000000;
srand(time(NULL));
for(m=0;m<9;m++){
c[m]=a[m];
}
while(times--){
for(m=0;m<9;m++){
if(a[m]==b[m]){
cnd=1;
}
else{
cnd=0;
break;
}
}
while(cnd==0){
i=rand()%9;
j=rand()%9;
if(prime(a[i],a[j])&&position(i,j)){
temp=a[i];
a[i]=a[j];
a[j]=temp;
count++;
for(m=0;m<9;m++){
if(a[m]==b[m]){
cnd=1;
}
else{
cnd=0;
break;
}
}
}
}
for(m=0;m<9;m++){
printf("%d ", a[m]);
a[m]=c[m];
}
if(count<finalcount){
finalcount=count;
}
printf("remaining = %d count= %d, finalcount= %d\n", times, count, finalcount);
count=0;
cnd=0;
}
return 0;
}
secondly i made another program. it targets the least number first i.e. 1, then it tries to bring it to the 0th position. if it fails to do so, then it goes to 2. and so on. it also is somehow able to solve basic problems (tough not in minimum ways) but not the more complex ones.
#include <stdio.h>
#include <stdlib.h>
int a[]={2,6,3,1,4,5,7,9,8},b[]={1,2,3,4,5,6,7,8,9},c[9];
int i,j,m,trgt=1,temp,cnt=0;
int prime(int a, int b){
int c=a+b;
if(c==3||c==5||c==7||c==11||c==13||c==17){
return 1;
}
return 0;
}
int position(int a, int b){
if((a-b==1||b-a==1||a-b==3||b-a==3) && (!((a==2&&b==3)||(a==3&&b==2)||(a==5&&b==6)||(a==6&&b==5))))
return 1;
else
return 0;
}
int condition(){
for(m=0;m<9;m++){
if(a[m]==b[m]);
else
return 1;
}
return 0;
}
int cond(){
if(a[trgt-1]==trgt)
return 0;
else
return 1;
}
int block(){
int p;
for(p=0;p<9;p++){
if(a[p]==c[p]);
else{
return 1;
}
}
return 0;
}
void target(int t){
for(m=0;m<9;m++){
c[m]=a[m];
printf("%d ", a[m]);
}
printf("\n");
while(cond()){
j=rand()%9;
if(prime(a[t],a[j])&&position(t,j)){
temp=a[t];
a[t]=a[j];
a[j]=temp;
t=j;
cnt++;
}
if(block()){
break;
}
}
}
int main()
{
while(condition()){
for(i=0;i<9;i++){
if(a[i]==trgt){
target(i);
trgt++;
}
}
trgt=1;
}
printf("Hello world!\n");
for(i=0;i<9;i++){
printf("%d ", a[i]);
}
return 0;
}
Please tell me what should i do?
The array is quite small - only 9 elements. This means its states are no more than 9! = 362880 (in fact not all of the 9! are possible but you can ignore this). Imagine you have a graph and you need to find the minimal number of edges that take you from a given vertex(the start position) to another vertex(the end position or the sorted array). Now problem seems easier, right? A simple breadth-first search and you are done! Now to solve the problem you don't have to actually build the graph - the representation you are given is enough. Make the vertices of your graph be represented by arrays and the edges are the possible swaps you can perform on the given array.

Resources