aboutsummaryrefslogtreecommitdiff
path: root/arithmetic_progression.c
diff options
context:
space:
mode:
authorjack <[email protected]>2024-06-14 13:13:15 -0600
committerjack <[email protected]>2024-06-14 13:13:15 -0600
commitd343a3b18dbaca9297d4f7b2280c4a16f0a5c8aa (patch)
tree96df922dae2a5073d9a50ea70c7aae6aa37e3ebe /arithmetic_progression.c
downloadleetcode-d343a3b18dbaca9297d4f7b2280c4a16f0a5c8aa.tar.gz
leetcode-d343a3b18dbaca9297d4f7b2280c4a16f0a5c8aa.zip
initial
Diffstat (limited to 'arithmetic_progression.c')
-rw-r--r--arithmetic_progression.c30
1 files changed, 30 insertions, 0 deletions
diff --git a/arithmetic_progression.c b/arithmetic_progression.c
new file mode 100644
index 0000000..6358900
--- /dev/null
+++ b/arithmetic_progression.c
@@ -0,0 +1,30 @@
+// 1502. Can Make Arithmetic Progression From Sequence
+#include <stdbool.h>
+#include <stdio.h>
+#include <stdlib.h>
+
+/*
+ * a sequence of numbers is called an arithmetic progression if the difference
+ * between any two consecutive elements is the same. gien an array of numbers
+ * 'arr', return true if the array can rearranged to form an arithmetic
+ * progression. otherwise, return false.
+ */
+
+int cmp(const void *a, const void *b) {
+ return *(const int *)a - *(const int *)b;
+}
+
+bool canMakeArithmeticProgression(int *arr, int arr_size) {
+ qsort(arr, arr_size, sizeof(int), cmp);
+ int diff = arr[1] - arr[0];
+ for (int i = 2; i < arr_size; i++)
+ if (arr[i] - arr[i - 1] != diff)
+ return false;
+ return true;
+}
+
+int main() {
+ int a1[] = {3, 5, 1}, a2[] = {1, 2, 4};
+ printf("%d\n", canMakeArithmeticProgression(a1, 3)); // expect: 1
+ printf("%d\n", canMakeArithmeticProgression(a2, 3)); // expect: 0
+}