Related
Trying to solve https://leetcode.com/problems/k-concatenation-maximum-sum/submissions/, I still got integer overflow when the data type is long
#include <stdlib.h>
#include <stdio.h>
#include <math.h>
int max(int a, int b) {
return a > b ? a : b;
}
int sum(int *nums, int numSize) {
int ans = 0;
for (int i = 0; i < numSize; ++i)
ans += nums[i];
return ans;
}
int KandaneAlgo(int *nums, int numSize) {
int i, max_overall_so_far = 0, max_ending_here = 0;
for (i = 0; i < numSize; ++i) {
max_ending_here += nums[i];
if (max_ending_here < 0)
max_ending_here = 0;
if (max_overall_so_far < max_ending_here)
max_overall_so_far = max_ending_here;
}
return max_overall_so_far;
}
int kConcatenationMaxSum(int *arr, int arrSize, int k) {
int mod = pow(10, 9) + 7;
int ans;
if (k > 1) {
long tem = (k - 2) * max(sum(arr, arrSize), 0);
int t1 = tem % mod;
printf("%ld, %d, %d \n", tem, t1, mod);
int arr2[2 * arrSize];
for (int i = 0; i < 2 * arrSize; ++i)
arr2[i] = arr[i - i / arrSize * arrSize];
ans = (int)t1 + KandaneAlgo(arr2, 2 * arrSize) % mod;
} else {
ans = KandaneAlgo(arr, arrSize) % mod;
}
return ans;
}
int main() {
int arr[10] = { [0 ... 9] = 10000 };
for (int i = 0; i < 10; ++i)
printf("%d ", arr[i]);
printf("\n");
int tot = kConcatenationMaxSum(arr, 10, 100000);
printf("%d \n", tot);
return 0;
}
I locally debug with lldb and can see the output message of variable tem is wrong indeed, it should be 9999800000.
This is because 9999800000 is larger than what can be stored in 32 bits. long only provides a minimum size guarantee of 32 bits. If you use long long for all the operands and result variable in the expression, it evaluates to the correct value. long long provides a minimum guarantee of 64 bits.
Check this for more details - https://en.wikipedia.org/wiki/C_data_types#Main_types
The following snippet worked for me:
long long tem = (long long)(k-2) * (long long)max(sum(arr, arrSize), 0);
Not sure about the rest of the algorithm, but this puts the correct value into tem.
I'm trying to randomize 4 different numbers in C and trying the next code:
{
int num1 = 0, num2 = 0, num3 = 0, num4 = 0;
int i = 0;
while (num1 == num2 && num1 == num3 && num1 == num4 && num2 == num3 && num2 == num4 && num3 == num4 && num3 == num2)
{
num1 = rand() % 7;
num2 = rand() % 7;
num3 = rand() % 7;
num4 = rand() % 7;
}
printf("%d %d %d %d\n", num1, num2, num3, num4);
}
The code suppose to check if the numbers are not equal and if they are equal, it needs to generate new numbers until they are all distinct.
But for some reason, it's not working well and even right numbers it puts them as wrong and it becomes and endless loop.
What am I missing?
This code will pick 4 different numbers in the range 0 .. 6, it works by creating an array of available numbers, as each is picked it is removed from the list.
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#define RANGE 7 // how many different numbers
#define PICK 4 // how many to pick
int main(void) {
int pool[RANGE];
int size, n, i;
for (size=0; size<RANGE; size++) {
pool[size] = size; // create number pool 0..6
}
srand((unsigned)time(NULL));
// pick different numbers
for(i=0; i<PICK; i++) {
n = rand() % size; // random array index
printf("%d ", pool[n]); // select number from pool
pool[n] = pool[--size]; // remove from pool
}
printf("\n");
return 0;
}
Try like this
void
get_random_values(int *values)
{
int source[] = {0, 1, 2, 3, 4, 5, 6};
for (int i = 0 ; i < 7 ; ++i)
{
int saved;
int j = rand() % 7;
int k = rand() % 7;
saved = source[j];
source[j] = source[k];
source[k] = saved;
}
values[0] = source[0];
values[1] = source[1];
values[2] = source[2];
values[3] = source[3];
}
int
main(void)
{
int values[4];
srand(time(NULL));
get_random_values(values);
for (int i = 0 ; i < 4 ; ++i)
fprintf(stderr, "%d ", values[i]);
fprintf(stderr, "\n");
return 0;
}
Don't forget to set the random seed srand() at the program startup or you will get the same sequence always.
To get a random, unbiased sequence:
#include <stdio.h>
#include <stdlib.h>
#define N 7
int main(int argc, char **argv)
{
// seed random number generator with first argument for easier testing
if (argc > 1) {
srand(atoi(argv[1]));
}
int array[N] = {0,1,2,3,4,5,6};
// Fisher–Yates shuffle:
// https://en.wikipedia.org/w/index.php?oldid=697311634#The_modern_algorithm
for (unsigned i = 0; i < N - 1; ++i) {
unsigned modulo = N - i;
// unbiased rand() % modulo:
// https://stackoverflow.com/a/10989061/416224
unsigned j;
do {
j = rand();
} while (j >= RAND_MAX - (RAND_MAX % modulo));
j %= modulo;
if (j > 0) {
int tmp = array[i];
array[i] = array[i + j];
array[i + j] = tmp;
}
}
for (unsigned i = 0; i < N; ++i) {
printf("%u. %d\n", i + 1, array[i]);
}
return 0;
}
Please follow the referenced links in the code.
I would suggest universal solution:
array of any size
lower and upper bounds sent as parameters.
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
void random(int* values, int amount, int lower_bound, int upper_bound)
{
int i=0, j=0, temp;
if(amount > upper_bound - lower_bound + 1)
return; // if there are more numbers than given bound
for(i=0; i<amount; )
{
temp = rand() % ( upper_bound - lower_bound + 1 ) + lower_bound;
for(j=i-1; j>=0; --j)
if(temp==values[j])
break;
if(temp==values[j])
continue;
values[i]=temp;
++i;
}
}
int main()
{
srand(time(NULL));
int arr[4]={0,0,0,0};
random(arr, 4, 5, 10);
for(int i=0; i<4; ++i)
printf("%d\n", arr[i]);
}
With this you can have (for example) 10 numbers of original values from -6 to 7.
Well, I wrote the code and everything is fine except one thing.
When I enter that digit number, which has to be upto 10 digits, I recieve in arr[0] various values, for example, if I enter "12345" I get 20, 1 , 1 , 1 , 1 , 1 , 0 ,0 ,0 ,0.
Which is fine from arr[1] to arr[9], but pretty odd in arr[0].
Any ideas?
#include <stdio.h>
#include <conio.h>
#include <math.h>
void main()
{
int i,j,p=0, temp,indexNum, arr[10] = { 0 }, num, level = 10, level2 = 1,maxIndex;
printf("Please enter a digit number (upto 10 digits) \n");
scanf("%d", &num);
temp = num;
while (temp > 0)
{
p++;
temp /= 10;
}
for (i = 0;i < p;i++)
{
temp = num;
while (temp > 0)
{
indexNum = num % level / level2;
arr[indexNum]++;
level *= 10;
level2 *= 10;
temp /= 10;
}
}
for (j = 0; j < 10; j++)
{
printf("%d\n", arr[j]);
}
getch();
}
Here is simplified version of your program:
#include <stdio.h>
#include <math.h>
int main()
{
int i = 0, j = 0, temp = 0, indexNum = 0, num = 0, level = 10;
int arr[10] = {0};
num = 7766123;
temp = num;
if(0 == temp) arr[0] = 1; // Handle 0 input this way
while (temp > 0)
{
indexNum = temp % level;
arr[indexNum]++;
temp /= 10;
}
for (j = 0; j < 10; j++)
{
printf("%d\n", arr[j]);
}
return 0;
}
A few hints to help you:
What does arr[10] = { 0 } actually do?
When you calculate indexNum, you are dividing integers. What happens when the modulus is a one-digit number, and level2 is greater than 1?
It's probably easier to read the input into a string and count digit characters. Something like this (not tested):
std::map<char, int> count;
std::string input;
std::cin >> input;
for (auto iter = input.begin(); iter != input.end(); ++iter) {
if (*iter < 0 || *iter > 9)
break;
else
++count[*iter];
}
for (auto iter = count.begin(); iter != count.end(); ++iter) {
std::cout << *iter << '\n';
}
You need to get rid of your first for loop. Something more like:
#include <stdio.h>
#include <math.h>
using namespace std;
int main()
{
int j;
int temp;
int indexNum;
int arr[10] = { 0 };
int num;
int level = 10;
int level2 = 1;
printf("Please enter a digit number (upto 10 digits) \n");
scanf("%d", &num);
temp = num;
while (temp > 0)
{
indexNum = num % level / level2;
arr[indexNum]++;
level *= 10;
level2 *= 10;
temp /= 10;
}
for (j = 0; j < 10; j++)
{
printf("%d\n", arr[j]);
}
return 0;
}
Check the program below.
void count_digits(unsigned int a, int count[])
{
unsigned int last_digit = 0;
if (a == 0) {
count[0] = 1;
}
while (a != 0)
{
last_digit = a%10;
count[last_digit]++;
a = a/10;
}
}
int main()
{
int count[10]= {0};
unsigned int num = 1122345; /* This is the input, Change it as per your need */
int i = 0;
count_digits(num, count);
for (i = 0; i < 10; i++)
{
printf ("%d: -- %d\n", i, count[i]);
}
return 0;
}
I am new to C and wondering why I am not getting any kind of output. I am trying to get my program to convert a hexadecimal number to binary.
#include <stdio.h>
#include <stdlib.h>
int* hex2binary(int hex_array[], int input_array_size, int* return_array_size) {
int hex_size = input_array_size;
int binary_array_size = 4 * hex_size;
int *binary_array = (int*) malloc(binary_array_size * sizeof(int));
int hex_index, binary_index;
for (hex_index = 0; hex_index < hex_size; hex_index++) {
int hex_num = hex_array[hex_index];
binary_index = hex_index * 4;
int bit_count;
for (bit_count = 3; bit_count <= 0; bit_count--) {
binary_array[binary_index + bit_count] = hex_num % 2;
hex_num = hex_num / 2;
}
hex_index++;
}
*return_array_size = binary_array_size;
return binary_array;
}
int main() {
char baseString[11];
int count = 0;
int i, j;
int original, wanted;
int size;
printf("Welcome to use this number base converter program.\n");
printf("Please input the original base: ");
scanf("%d", &original);
printf("Please input a base-%d number with more more than 10 digits: ",
original);
scanf("%s", baseString);
while (baseString[count] != '\0')
count++;
int *baseNumber = (int*) malloc(count * sizeof(int));
for (i = 0; i < count; i++) {
baseNumber[i] =
baseString[i] <= '9' ? baseString[i] - '0' : baseString[i] - 'A' + 10;
}
int* result_array;
printf("Please input the target base: ");
scanf("%d", &wanted); //doesn't read anything past this point
printf("Target base: %d", wanted);
if (original == 16) {
if (wanted == 2) {
result_array = hex2binary(baseNumber, count, size);
for (j = 0; j < size; j++) {
printf("Result: %d", result_array[j]);
}
}
}
}
I know it can't be something to difficult, but I can't seem to figure out why it isn't even producing some kind of output.
This line
result_array = hex2binary(baseNumber, count, size);
is incorrect because this function needs a pointer argument
int* hex2binary(int hex_array[], int input_array_size, int* return_array_size)
So it should be called like this
result_array = hex2binary(baseNumber, count, &size); // note the &
Then the subsequent loop
for (j = 0; j < size; j++)
will no longer be using the uninitialised variable size.
Please help me to solve this task:
Generate all binary strings of length n with k bits set.(need to write on C)
for example:
n=5
k=3
11100
00111
11010
01011
**01110
11001
10011
**01101
**10110
10101
** can't generate these permutations
Code:
#include <stdio.h>
#define N 10
int main (void)
{
int mas[N]={0},kst,m,n1,z,a,b;
printf("\n\nVvedit` rozmirnist` masyvu: ");
scanf("%d",&kst);
printf("\n\nVvedit` kil`kist` odynyc`: ");
scanf("%d",&n1);
for(m=0;m1;m++)
mas[m]=1;
for(m=0;m<kst;m++)
printf("%d",mas[m]);
printf("\n");
for(m=0;m<n1;m++){
for(z=0;z<(kst-1);z++)
if((mas[z]==1) && (mas[z+1]==0)){
a=mas[z];
mas[z]=mas[z+1];
mas[z+1]=a;
for(b=0;b<kst;b++)
printf("%d",mas[b]);
printf("\n");
}
}
return 0;
}
I have solved this problem earlier! please find my code below! I hope this will help you out.
#include<stdio.h>
int NumberOfBitsSet(int number)
{
int BitsSet = 0;
while(number != 0)
{
if(number & 0x01)
{
BitsSet++;
}
number = number >> 1;
}
return BitsSet;
}
void PrintNumberInBinary(int number, int NumBits)
{
int val;
val = 1 << NumBits; // here val is the maximum possible number of N bits with only MSB set
while(val != 0)
{
if(number & val)
{
printf("1");
}
else
{
printf("0");
}
val = val >> 1;
}
}
int main()
{
int n,k,i;
int max,min;
printf("enter total number of bits and number of bits to be set:\n");
scanf("%d %d", &n, &k);
min = ((1 << k) - 1); //min possible values with k bits set
max = (min << (n-k)); //max possible value with k bits set!
//printf("%d %d", min, max);
for(i=0; i<= max; i++)
{
if(!(i<min))
{
if(NumberOfBitsSet(i) == k)
{
PrintNumberInBinary(i, (n-1));
printf("\n");
}
}
}
return 0;
}
Your code is a mess ;)
Seriously: first rule when solving a task in code is to write clean code, use sensible variable naming etc.
For tasks like this one I would suggest using this.
Now to your sample code: it would not compile and it is hard to read what you are trying to do. Formatted and with some comments:
#include <stdio.h>
#define N 10
int main(void)
{
int mas[N] = {0};
int kst, m, n1, z, a, b;
/* Read width ? */
printf("\n\nVvedit` rozmirnist` masyvu: ");
scanf("%d", &kst);
/* Read number of bit's set? */
printf("\n\nVvedit` kil`kist` odynyc`: ");
scanf("%d", &n1);
/* m1 is not defined, thus the loop give no meaning.
* Guess you are trying to set "bits" integers to 1.
*/
for (m = 0; m1; m++)
mas[m] = 1;
/* This should be in a function as 1. You do it more then once, and
* 2. It makes the code much cleaner and easy to maintain.
*/
for (m = 0; m < kst; m++)
printf("%d", mas[m]);
printf("\n");
for (m = 0; m < n1; m++) {
for (z = 0; z < (kst - 1); z++) {
if ((mas[z] == 1) && (mas[z + 1] == 0)) {
a = mas[z]; /* Same as a = 1; */
mas[z] = mas[z + 1]; /* Same as mas[z] = 0; */
mas[z + 1] = a; /* Same as mas[z + 1] = 1; */
/* Put this into a function. */
for (b = 0; b < kst; b++)
printf("%d", mas[b]);
printf("\n");
}
}
}
return 0;
}
The extensive use of printf when one are not sure of what is going on is a precious tool.
This is not a solution, (it is basically doing the same as your post, but split up), but a sample of something that might be easier to work with. I have also used a char array as C-string instead of integer array. Easier to work with in this situation.
If you want to use integer array I'd suggest you add a print_perm(int *perm, int width) helper function to get it out of the main code.
#include <stdio.h>
#define MAX_WIDTH 10
int get_spec(int *width, int *bits)
{
fprintf(stderr, "Enter width (max %-2d): ", MAX_WIDTH);
scanf("%d", width);
if (*width > MAX_WIDTH) {
fprintf(stderr, "Bad input: %d > %d\n", *width, MAX_WIDTH);
return 1;
}
fprintf(stderr, "Enter set bits (max %-2d): ", *width);
scanf("%d", bits);
if (*bits > MAX_WIDTH) {
fprintf(stderr, "Bad input: %d > %d\n", *bits, MAX_WIDTH);
return 1;
}
return 0;
}
void permutate(int width, int bits)
{
char perm[MAX_WIDTH + 1];
int i, j;
/* Set "bits" */
for (i = 0; i < width; ++i)
perm[i] = i < bits ? '1' : '0';
/* Terminate C string */
perm[i] = '\0';
fprintf(stderr, "\nPermutations:\n");
printf("%s\n", perm);
for (i = 0; i < bits; ++i) {
/* Debug print current perm and outer iteration number */
printf("%*s LOOP(%d) %s\n",
width, "", i, perm
);
for (j = 0; j < (width - 1); ++j) {
if (perm[j] == '1' && perm[j + 1] == '0') {
perm[j] = '0';
perm[j + 1] = '1';
printf("%s j=%d print\n",
perm, j
);
} else {
/* Debug print */
printf("%*s j=%d skip %s\n",
width, "", j, perm
);
}
}
}
}
int main(void)
{
int width, bits;
if (get_spec(&width, &bits))
return 1;
permutate(width, bits);
return 0;
}
If you want to list all of the permutations uniquely without doing "iterate and check", you can do something like this:
# Move peg x up m using s
# x is negative
# m is positive
def move(x, m, s):
for i in range(1, m+1):
s2 = list(s)
s2[x] = 0
s2[x - i] = 1
print(s2)
if x + 1 < 0:
move(x+1, i, s2)
# Print all unique permutations of
# n bits with k ones (and n-k zeros)
def uniqPerms(n, k):
s = [0 for _ in range(n-k)] + [1 for _ in range(k)]
print(s)
move(-k, n-k, s)
if __name__ == '__main__':
from sys import argv
uniqPerms(int(argv[1]), int(argv[2]))
The idea is that you inch the 1's up recursively, so that each movement produces a unique list (since a 1 is now somewhere none was before).
And you said it must be in C:
#include <stdio.h>
#include <stdlib.h>
enum { n = 8 };
struct string
{
char str[n + 1];
};
void move(int x, int m, string s)
{
for (int i = 0; i <= m; ++i)
{
string s2 = s;
s2.str[n + x] = '0';
s2.str[n + x - i] = '1';
printf("%s\n", s2.str);
if (x + 1 < 0)
move(x + 1, i, s2);
}
}
void uniqPerms(int k)
{
string s;
for (int i = 0; i < n - k; ++i)
s.str[i] = '0';
for (int i = n - k; i < n; ++i)
s.str[i] = '1';
s.str[n] = '\0';
printf("%s\n", s.str);
move(-k, n - k, s);
}
int main(int argc, char *argv[])
{
uniqPerms(atoi(argv[1]));
return 0;
}
try this
A[n-1]=0;
func(n-1);
A[n-1]=1;
func(n-1);
//Think simple people but please bear with me i love java
//Assume array A is globally defined
void Binary(int n)
{
if(n<1)
{
System.out.println(A);
}
else
{
A[n-1]=0;
Binary(n-1);
A[n-1]=1;
Binary(n-1);
}
}
here is the recursive solution
#include <iostream>
#include <vector>
using namespace std;
char v[4];
int count = 0;
void printString(){
int i;
for(i = 0; i < 4; i++){
cout << v[i] << " ";
}
cout <<count << endl;
}
void binary(int n){
if(n < 0){
if(count == 2)
printString();
}
else{
v[n] = '0';
binary(n - 1);
v[n] = '1';
count++;
binary(n-1);
count--;
}
}
int main(){
binary(3);
return 0;
}
#include<stdio.h>
int main(){
int n,k,i,j,a[50];
//lets suppose maximum size is 50
printf("Enter the value for n");
scanf("%d",&n);
printf("Enter the value for k");
scanf("%d",&k);
//create an initial bitstring of k 1's and n-k 0's;
for(i=0;i<n;i++){
if(k>0)
a[i]=1;
else
a[i]=0;
k--;
}
for(i=0;i<n;i++){
if(a[i]==1){
for(j=0;j<n;j++){
if(j!=i&&a[j]==0){
a[j]=1;a[i]=0;
for(k=0;k<n;k++){printf("%d\n",a[k]);}
a[i]=1; a[j]=0;
}}}}
return 0;
}
**If Complexity doesn't matter you can use the following code which are done in java. which will provide the desired output in o(2^n).Here I have find all the combination of 0 and 1 for the given n bits in array of size n.In case of K bit is set I have counted the number of 1 presented is equal to k using countBits() funtion.if so I have printed that array.
public class GenerateAllStringOfNBitsWithKBitsSet {
public static int a[] ={0,0,0,0,0};
static int k=3;
public static boolean countBits(){
int y=0;
for(int i=0;i<a.length;i++)
y += a[i] & 1 ;
if(y==k)
return true;
return false;
}
public static void gen(int n)
{
if(n<1)
{
if(countBits())
System.out.println(Arrays.toString(a));
}
else
{
a[n-1]=0;
gen(n-1);
a[n-1]=1;
gen(n-1);
}
}
public static void main(String[] args) {
GenerateAllStringOfNBitsWithKBitsSet.gen(a.length);
}
}