How to sort an array - arrays

I have problem for sorting my array in Go,
Here is my code :
func main() {
fmt.Print("Masukkan Jumlah Data yang akan dimasukkan: ")
var jumlahdata int
fmt.Scanln(&jumlahdata)
var DataDiagram = make([]int, jumlahdata)
fmt.Print("Masukkan data secara berurutan dengan spasi sebagai pemisah antar angka: ")
for i := 0; i < jumlahdata; i++ {
fmt.Scanf("%d", &DataDiagram[i])
}
fmt.Print("\n")
var max int = DataDiagram[0]
for _, value := range DataDiagram { // Menemukan nilai maximum
if value > max {
max = value
}
}
var mem int
Sorting(DataDiagram, jumlahdata, mem, max)
}
func Grafik(jumlahdata int, max int, DataDiagram []int) {
for i := max; i >= 1; i-- { // membuat Data Diagram
for j := 0; j < jumlahdata; j++ {
if DataDiagram[j] >= i {
fmt.Print(" | ")
} else {
fmt.Print(" ")
}
}
fmt.Print("\n")
}
for i := 0; i < jumlahdata; i++ {
fmt.Print("---")
}
fmt.Print("\n")
fmt.Print(" ")
for i := 0; i < jumlahdata; i++ {
fmt.Print(DataDiagram[i], " ")
}
}
func Sorting(DataDiagram []int, jumlahdata int, mem int, max int) {
for langkah := 0; langkah < (jumlahdata-1) ; langkah++ {
Grafik(jumlahdata, max, DataDiagram)
for i := 0; i < jumlahdata - (langkah-1); i++ {
if DataDiagram[i] > DataDiagram[i + 1] {
mem := DataDiagram[i];
DataDiagram[i] = DataDiagram[i + 1]
DataDiagram[i + 1] = mem;
}
}
}
}
What i expect is look like this:
What I Expect
But the output said otherwise, it give me error : It give me error
Can someone give some guide how to fix this :) i just learn Go yesterday, it similiar to C, but keep giving me index out of range error

I understand your task is to sort an int "array" (slice, in go-speak), showing each step of your work as a graph. Because you must show your work, you can't use go's built-in sorting, e.g. sort.Ints(DataDiagram).
Your problems are with the Sorting function.
Step 1 Your immediate crash-causing problem is that i eventually iterates to a number larger than upper index of DataDiagram. That we fix in the commented line below.
// Step 1: fix the iterator
func Sorting(DataDiagram []int, jumlahdata int, mem int, max int) {
for langkah := 0; langkah < (jumlahdata-1) ; langkah++ {
Grafik(jumlahdata, max, DataDiagram)
for i := 0; i < jumlahdata - 1; i++ { // Was: for i := 0; i < jumlahdata - (langkah-1); i++ {
if DataDiagram[i] > DataDiagram[i + 1] {
mem := DataDiagram[i];
DataDiagram[i] = DataDiagram[i + 1]
DataDiagram[i + 1] = mem;
}
}
}
}
Step 2 The code no longer crashes, but is not guaranteed to sort, because it makes only one pass through the inputs. We need to continue looping until there's no more swapping taking place. That problem is fixed below. The code now produces the expected output on the playground.
// Step 2: loop until sorted
func Sorting(DataDiagram []int, jumlahdata int, mem int, max int) {
swapped := true
for swapped {
Grafik(jumlahdata, max, DataDiagram)
swapped = false
for i := 0; i < jumlahdata - 1; i++ {
if DataDiagram[i] > DataDiagram[i + 1] {
mem := DataDiagram[i];
DataDiagram[i] = DataDiagram[i + 1]
DataDiagram[i + 1] = mem;
swapped = true
}
}
}
}
Step 3 The above code works fine, but perhaps can use some tidying. The end result is unchanged on the playground.
// Step 3: make it prettier
func Sorting(data []int) {
max := data[0]
for _, value := range data { // Menemukan nilai maximum
if value > max {
max = value
}
}
swapped := true
for swapped {
Grafik(len(data), max, data)
swapped = false
for i := 0; i < len(data)-1; i++ {
if data[i] > data[i+1] {
data[i], data[i+1] = data[i+1], data[i]
swapped = true
}
}
}
}

It's much simpler if you would just use
sort.Ints(ints), which you can see here:
https://goplay.space/#i9VIrDG-vL-

Related

Converting something to bytes

I want to convert a variable (I took an int for this example) to a byte using this code that I have found:
func IntToByteArray(num int64) []byte {
size := int(unsafe.Sizeof(num))
arr := make([]byte, size)
for i := 0 ; i < size ; i++ {
byt := *(*uint32)(unsafe.Pointer(uintptr(unsafe.Pointer(&num)) + uintptr(i)))
arr[i] = byte(byt)
}
return arr
}
func main(){
println(IntToByteArray(1456))
}
But the output that it gives me is this one : [8/8]0xc00001a0d0
Can some one explain me why do I have this has a result?
And what is exactly a byte array?
package main
import "fmt"
func IntToByteArray(num int64) []byte {
r := make([]byte, 8)
for i := 0; i < len(r); i++ {
r[i] = byte(num >> (i * 8) & 255)
}
return r
}
func main() {
fmt.Println(IntToByteArray(65280))
}
This assumes little-endianness.
As others have suggested, the included packages are more flexible and tested.

Need help to solve challenging Data structure problem

I came across this problem where given an array of integers, tell if the sequence of
integers will exit the array from left, right or
deadend. You enter the array from the left and move
N indices(where N is the value of the integer) in the
specified direction(positive is right, negative
is left)
Examples
[1,1,1] -> Exits Right
[1,-2]=> Exits Left
[2,0,-1]-> Deadends
[2,5,1,-2,0]-> Exits Right
One solution which comes to my mind is if value of all integers are positive then
Exits Right or Exits Left. However this solution does not cover all the scenario.
I need help to solve this problem.
You can do this:
Create a variable to hold index position and initialize it with first value
Loop over array and on every iteration, compute new value of index by adding value of pointed index.
At the end of loop, check:
Right: If index >= array.length`
Left: if index < 0
Deadend: If index is in bounds
Based on this, below is an example using Javascript:
function printDirection(arr) {
let index = arr[0];
for (let i = 1; i < arr.length; i++) {
/**
* Below condition covers following cases:
* 1. If the value is undefined. This will happen if index is out of bound
* 2. If value is 0. In this case, `index` will never change and remaining iterations can be skipped
*/
if (!arr[index]) break;
index += arr[index]
}
if (index >= arr.length) {
console.log('Exit Right')
} else if (index < 0) {
console.log('Exit Left')
} else {
console.log('Deadend')
}
}
const data = [
[1, 1, 1],
[1, -2],
[2, 0, -1],
[2, 5, 1, -2, 0],
]
data.forEach((arr) => printDirection(arr))
Here some hacky golang:
package main
import (
"fmt"
)
func WhereIsTheExit(arr []int) {
if (len(arr) == 0) {
fmt.Println("No elements")
return
}
i := arr[0]
for p := 1; p < len(arr); p++ {
fmt.Printf("Current value: %d\n", i)
if (i > len(arr) - 1 || i < 0) {
break
}
i += arr[i]
fmt.Printf("Next value: %d\n", i)
}
if (i >= len(arr)) {
fmt.Println("====> right")
} else if (i < 0) {
fmt.Println("====> left")
} else {
fmt.Println("====> deadend")
}
}
func main() {
empty := []int{}
deadend := []int{1,2,0,-3}
deadend2 := []int{1,0,-1}
right := []int{2,0,3,0,0}
right2 := []int{1,2,0,4,0,2,7,1}
left := []int{1,-2}
left2 := []int{1,2,0,3,0,0,-10}
WhereIsTheExit(empty)
WhereIsTheExit(deadend)
WhereIsTheExit(deadend2)
WhereIsTheExit(right)
WhereIsTheExit(right2)
WhereIsTheExit(left)
WhereIsTheExit(left2)
}
Try out: https://play.golang.org/p/KU4mapYf_b3

Sum of squares in an array using recursion in golang

So my friend gave me this task where the sum of squares of positive numbers must be calculated using recursion.
Conditions - The input will be a string with space separated numbers
This is what I've come so far but this shows a runtime error.
Here is the full error https://ideone.com/53oOjN
package main
import(
'fmt',
'strings',
'strconv'
)
var n int = 4
var sum_of_squares int = 0
func sumOfSquares(strArray []string, iterate int) int{
number, _ := strconv.Atoi(strArray[iterate])
if number > 0 {
sum_of_squares += number*number
}
if iterate == n {
return 0 // just to end the recursion
}
return sumOfSquares(strArray, iterate+1)
}
func main() {
str := "1 2 3 4"
strArray := strings.Fields(str)
result := sumOfSquares(strArray, 0)
fmt.Println(sum_of_squares, result)
}
The rule of thumb in recursion is termination condition. It should exist and it should exist in the right place.
func sumOfSquares(strArray []string, iterate int) int{
if iterate >= len(strArray) {
return sum_of_squares
}
number, _ := strconv.Atoi(strArray[iterate]) //TODO: handle err here
sum_of_squares += number*number
return sumOfSquares(strArray, iterate+1)
}
Just for you information: canonical recursion should not save it's state into global fields. I would suggest using following function signature.
func sumOfSquares(strArray []string, iterate, currentSum int) int{
//...
return sumOfSquares(strArray, iterate+1, sum_of_squares)
}
So that you don't need to store sum_of_squares somewhere. You will just pass it to next function invocation.
package main
import (
"fmt"
"strconv"
"strings"
)
var n int
func sumOfSquares(strArray []string, iterate int) int {
number, _ := strconv.Atoi(strArray[iterate])
if iterate == n {
return number * number
}
return ((number * number) + sumOfSquares(strArray, iterate+1))
}
func main() {
str := "1 2 3 4"
strArray := strings.Fields(str)
n = len(strArray) - 1
result := sumOfSquares(strArray, 0)
fmt.Println(result)
}
Indexing starts from 0, so decrease the length by one.
As #peterSO have pointed out, if strings contain unusual characters, it doesn't work, I didn't post the right answer for getting input because you seem to be beginner, but you can read the input, like this instead.
var inp []byte
var loc int
inp, _ = ioutil.ReadFile(fileName)
//add \n so that we don't end up running out of bounds,
//if last byte is integer.
inp = append(inp, '\n')
func scanInt() (res int) {
if loc < len(inp) {
for ; inp[loc] < 48 || inp[loc] > 57; loc++ {
}
for ; inp[loc] > 47 && inp[loc] < 58; loc++ {
res = res<<3 + res<<1 + (int(inp[loc]) - 48)
}
}
return
}
This is faster and scans integers only, and skips all other unusual characters.
I like to keep it simple. I have some few if conditions as well, but hope you like it.
func sumOfSquares(numArr []string) int {
i, err := strconv.Atoi(numArr[0])
rest := numArr[1:]
//Error checking
if err != nil {
fmt.Println(err)
os.Exit(1)
return 0
}
square := i * i
// negative & last number
if i < 0 && len(rest) == 0 {
return square
}
// negative & not last number
if i < 0 && len(rest) > 0 {
return sumOfSquares(rest)
}
// last man standing
if i >= 0 && len(rest) == 0 {
return square
}
return square + sumOfSquares(rest)
}
DEMO : https://play.golang.org/p/WWYxKbvzanJ

Given a list of numbers and a number k, return whether any two numbers from the list add up to k

This question was asked in the Google programming interview. I thought of two approaches for the same:
Find all the subsequences of length. While doing so compute the sum and of the two elements and check if it is equal to k. If ye, print Yes, else keep searching. This is a brute Force approach.
Sort the array in non-decreasing order. Then start traversing the array from its right end. Say we have the sorted array, {3,5,7,10} and we want the sum to be 17. We will start from element 10, index=3, let's denote the index with 'j'. Then include the current element and compute required_sum= sum - current_element. After that, we can perform a binary or ternary search in array[0- (j-1)] to find if there is an element whose value is equal to the required_sum. If we find such an element, we can break as we have found a subsequence of length 2 whose sum is the given sum. If we don't find any such element, then decrease the index of j and repeat the above-mentioned steps for resulting subarray of length= length-1 i.e. by excluding the element at index 3 in this case.
Here we have considered that array could have negative as well as positive integers.
Can you suggest a better solution than this? A DP solution maybe? A solution that can further reduce it's time complexity.
This question can be easily solved with the help of set in O(N) time and space complexity.First add all the elements of array into set and then traverse each element of array and check whether K-ar[i] is present in set or not.
Here is the code in java with O(N) complexity :
boolean flag=false;
HashSet<Long> hashSet = new HashSet<>();
for(int i=0;i<n;i++){
if(hashSet.contains(k-ar[i]))flag=true;
hashSet.add(ar[i]);
}
if(flag)out.println("YES PRESENT");
else out.println("NOT PRESENT");
Here is a Java implementation with the same time complexity as the algorithm used to sort the array. Note that this is faster than your second idea because we do not need to search the entire array for a matching partner each time we examine a number.
public static boolean containsPairWithSum(int[] a, int x) {
Arrays.sort(a);
for (int i = 0, j = a.length - 1; i < j;) {
int sum = a[i] + a[j];
if (sum < x)
i++;
else if (sum > x)
j--;
else
return true;
}
return false;
}
Proof by induction:
Let a[0,n] be an array of length n+1 and p = (p1, p2) where p1, p2 are integers and p1 <= p2 (w.l.o.g.). Assume a[0,n] contains p1 and p2. In the case that it does not, the algorithm is obviously correct.
Base case (i = 0, j = n):
a[0,-1] does not contain p1 and a[n,n+1] does not contain p2.
Hypothesis:
a[0,i-1] does not contain a[i] and a[j+1,n] does not contain p2.
Step case (i to i + 1 or j to j - 1):
Assume p1 = a[i]. Then, since p1 + a[j] < p1 + p2, index j must be increased. But from the hypothesis we know that a[j+1,n-1] does not contain p2. Contradiction. It follows that p1 != a[i].
j to j - 1 analogously.
Because each iteration, a[0,i-1] and a[j+1,n], does not contain p1, and p2, a[i,j] does contain p1 and p2. Eventually, a[i] = p1 and a[j] = p2 and the algorithm returns true.
This is java implementation with O(n) Time complexity and O(n) space. The idea is have a HashMap which will contain complements of every array element w.r.t target. If the complement is found, we have 2 array elements which sum to the target.
public boolean twoSum(int[] nums, int target) {
if(nums.length == 0 || nums == null) return false;
Map<Integer, Integer> complementMap = new HashMap<>();
for (int i = 0; i < nums.length; i++) {
int curr = nums[i];
if(complementMap.containsKey(target - curr)){
return true;
}
complementMap.put(curr, i);
}
return false;
}
if you want to find pair count,
pairs = [3,5,7,10]
k = 17
counter = 0
for i in pairs:
if k - i in pairs:
counter += 1
print(counter//2)
Python Solution:
def FindPairs(arr, k):
for i in range(0, len(arr)):
if k - arr[i] in arr:
return True
return False
A = [1, 4, 45, 6, 10, 8]
n = 100
print(FindPairs(A, n))
Or
def findpair(list1, k):
for i in range(0, len(list1)):
for j in range(0, len(list1)):
if k == list1[i] + list1[j]:
return True
return False
nums = [10, 5, 6, 7, 3]
k = 100
print(findpair(nums, k))
Here is python's implementation
arr=[3,5,7,10]
k=17
flag=False
hashset = set()
for i in range(0,len(arr)):
if k-arr[i] in hashset:
flag=True
hashset.add(arr[i])
print( flag )
Javascript solution:
function hasSumK(arr, k) {
hashMap = {};
for (let value of arr) {
if (hashMap[value]) { return true;} else { hashMap[k - value] = true };
}
return false;
}
Using Scala, in a single pass with O(n) time and space complexity.
import collection.mutable.HashMap
def addUpToK(arr: Array[Int], k: Int): Option[Int] = {
val arrayHelper = new HashMap[Int,Int]()
def addUpToKHelper( i: Int): Option[Int] = {
if(i < arr.length){
if(arrayHelper contains k-arr(i) ){
Some(arr(i))
}else{
arrayHelper += (arr(i) -> (k-arr(i)) )
addUpToKHelper( i+1)
}
}else{
None
}
}
addUpToKHelper(0)
}
addUpToK(Array(10, 15, 3, 7), 17)
C++ solution:
int main(){
int n;
cin>>n;
int arr[n];
for(int i = 0; i < n; i++)
{
cin>>arr[i];
}
int k;
cin>>k;
int t = false;
for(int i = 0; i < n-1; i++)
{
int s = k-arr[i];
for(int j = i+1; j < n; j++)
{
if(s==arr[j])
t=true;
}
}
if (t){
cout<<"Thank you C++, very cool";
}
else{
cout<<"Damn it!";
}
return 0;
}
Python code:
L = list(map(int,input("Enter List: ").split()))
k = int(input("Enter value: "))
for i in L:
if (k - i) in L:
print("True",k-i,i)
Here is Swift solution:
func checkTwoSum(array: [Int], k: Int) -> Bool {
var foundPair = false
for n in array {
if array.contains(k - n) {
foundPair = true
break
} else {
foundPair = false
}
}
return foundPair
}
def sum_total(list, total):
dict = {}
for i in lista:
if (total - i) in dict:
return True
else:
dict[i] = i
return False
Here is a C implementationFor Sorting O(n2) time and space complexity.For Solving Problem We use
single pass with O(n) time and space complexity via Recursion.
/* Given a list of numbers and a number k , return weather any two numbers from the list add up to k.
For example, given [10,15,3,7] and k of 17 , return 10 + 7 is 17
Bonus: Can You Do in one pass ? */
#include<stdio.h>
int rec(int i , int j ,int k , int n,int array[])
{
int sum;
for( i = 0 ; i<j ;)
{
sum = array[i] + array[j];
if( sum > k)
{
j--;
}else if( sum < k)
{
i++;
}else if( sum == k )
{
printf("Value equal to sum of array[%d] = %d and array[%d] = %d",i,array[i],j,array[j]);
return 1;//True
}
}
return 0;//False
}
int main()
{
int n ;
printf("Enter The Value of Number of Arrays = ");
scanf("%d",&n);
int array[n],i,j,k,x;
printf("Enter the Number Which you Want to search in addition of Two Number = ");
scanf("%d",&x);
printf("Enter The Value of Array \n");
for( i = 0 ; i <=n-1;i++)
{
printf("Array[%d] = ",i);
scanf("%d",&array[i]);
}
//Sorting of Array
for( i = 0 ; i <=n-1;i++)
{
for( j = 0 ; j <=n-i-1;j++)
{
if( array[j]>array[j+1])
{
//swapping of two using bitwise operator
array[j] = array[j]^array[j+1];
array[j+1] = array[j]^array[j+1];
array[j] = array[j]^array[j+1];
}
}
}
k = x ;
j = n-1;
rec(i,j,k,n,array);
return 0 ;
}
OUTPUT
Enter The Value of Number of Arrays = 4
Enter the Number Which you Want to search in addition of Two Number = 17
Enter The Value of Array
Array[0] = 10
Array[1] = 15
Array[2] = 3
Array[3] = 7
Value equal to sum of array[1] = 7 and array[2] = 10
Process returned 0 (0x0) execution time : 54.206 s
Press any key to continue.
The solution can be found out in just one pass of the array. Initialise a hash Set and start iterating the array. If the current element in the array is found in the set then return true, else add the complement of this element (x - arr[i]) to the set. If the iteration of array ended without returning it means that there is no such pair whose sum is equal to x so return false.
public boolean containsPairWithSum(int[] a, int x) {
Set<Integer> set = new HashSet<>();
for (int i = 0; i< a.length; i++) {
if(set.contains(a[i]))
return true;
set.add(x - a[i]);
}
return false;
}
Here's Python. O(n). Need to remove the current element whilst looping because the list might not have duplicate numbers.
def if_sum_is_k(list, k):
i = 0
list_temp = list.copy()
match = False
for e in list:
list_temp.pop(i)
if k - e in list_temp:
match = True
i += 1
list_temp = list.copy()
return match
I came up with two solutions in C++. One was a naive brute force type which was in O(n^2) time.
int main() {
int N,K;
vector<int> list;
cin >> N >> K;
clock_t tStart = clock();
for(int i = 0;i<N;i++) {
list.push_back(i+1);
}
for(int i = 0;i<N;i++) {
for(int j = 0;j<N;j++) {
if(list[i] + list[j] == K) {
cout << list[i] << " " << list[j] << endl;
cout << "YES" << endl;
printf("Time taken: %.2fs\n", (double)(clock() - tStart)/CLOCKS_PER_SEC);
return 0;
}
}
}
cout << "NO" << endl;
printf("Time taken: %f\n", (double)(clock() - tStart)/CLOCKS_PER_SEC);
return 0;}
This solution as you could imagine will take a large amount of time on higher values of input.
My second solution I was able to implement in O(N) time. Using an unordered_set, much like the above solution.
#include <iostream>
#include <unordered_set>
#include <time.h>
using namespace std;
int main() {
int N,K;
int trig = 0;
int a,b;
time_t tStart = clock();
unordered_set<int> u;
cin >> N >> K;
for(int i = 1;i<=N;i++) {
if(u.find(abs(K - i)) != u.end()) {
trig = 1;
a = i;
b = abs(K - i);
}
u.insert(i);
}
trig ? cout << "YES" : cout << "NO";
cout << endl;
cout << a << " " << b << endl;
printf("Time taken %fs\n",(double) (clock() - tStart)/CLOCKS_PER_SEC);
return 0;
}
Python Implementation:
The code would execute in O(n) complexity with the use of dictionary. We would be storing the (desired_output - current_input) as the key in the dictionary. And then we would check if the number exists in the dictionary or not. Search in a dictionary has an average complexity as O(1).
def PairToSumK(numList,requiredSum):
dictionary={}
for num in numList:
if requiredSum-num not in dictionary:
dictionary[requiredSum-num]=0
if num in dictionary:
print(num,requiredSum-num)
return True
return False
arr=[10, 5, 3, 7, 3]
print(PairToSumK(arr,6))
Javascript
const findPair = (array, k) => {
array.sort((a, b) => a - b);
let left = 0;
let right = array.length - 1;
while (left < right) {
const sum = array[left] + array[right];
if (sum === k) {
return true;
} else if (sum < k) {
left += 1;
} else {
right -= 1;
}
}
return false;
}
Using HashSet in java we can do it in one go or with time complexity of O(n)
import java.util.Arrays;
import java.util.HashSet;
public class One {
public static void main(String[] args) {
sumPairsInOne(10, new Integer[]{8, 4, 3, 7});
}
public static void sumPairsInOne(int sum, Integer[] nums) {
HashSet<Integer> set = new HashSet<Integer>(Arrays.asList(nums));
//adding values to a hash set
for (Integer num : nums) {
if (set.contains(sum - num)) {
System.out.print("Found sum pair => ");
System.out.println(num + " + " + (sum - num) + " = " + sum);
return;
}
}
System.out.println("No matching pairs");
}
}
Python
def add(num, k):
for i in range(len(num)):
for j in range(len(num)):
if num[i] + num[j] == k:
return True
return False
C# solution:
bool flag = false;
var list = new List<int> { 10, 15, 3, 4 };
Console.WriteLine("Enter K");
int k = int.Parse(Console.ReadLine());
foreach (var item in list)
{
flag = list.Contains(k - item);
if (flag)
{
Console.WriteLine("Result: " + flag);
return;
}
}
Console.WriteLine(flag);
My C# Implementation:
bool isPairPresent(int[] numbers,int value)
{
for (int i = 0; i < numbers.Length; i++)
{
for (int j = 0; j < numbers.Length; j++)
{
if (value - numbers[i] == numbers[j])
return true;
}
}
return false;
}
Here's a javascript solution:
function ProblemOne_Solve()
{
const k = 17;
const values = [10, 15, 3, 8, 2];
for (i=0; i<values.length; i++) {
if (values.find((sum) => { return k-values[i] === sum} )) return true;
}
return false;
}
I implemented with Scala
def hasSome(xs: List[Int], k: Int): Boolean = {
def check(xs: List[Int], k: Int, expectedSet: Set[Int]): Boolean = {
xs match {
case List() => false
case head :: _ if expectedSet contains head => true
case head :: tail => check(tail, k, expectedSet + (k - head))
}
}
check(xs, k, Set())
}
I have tried the solution in Go Lang. However, it consumes O(n^2) time.
package main
import "fmt"
func twoNosAddUptoK(arr []int, k int) bool{
// O(N^2)
for i:=0; i<len(arr); i++{
for j:=1; j<len(arr);j++ {
if arr[i]+arr[j] ==k{
return true
}
}
}
return false
}
func main(){
xs := []int{10, 15, 3, 7}
fmt.Println(twoNosAddUptoK(xs, 17))
}
Here's two very quick Python implementations (which account for the case that inputs of [1,2] and 2 should return false; in other words, you can't just double a number, since it specifies "any two").
This first one loops through the list of terms and adds each term to all of the previously seen terms until it hits the desired sum.
def do_they_add(terms, result):
first_terms = []
for second_term in terms:
for first_term in first_terms:
if second_term + first_term == result:
return True
first_terms.append(second_term)
return False
This one subtracts each term from the result until it reaches a difference that is in the list of terms (using the rule that a+b=c -> c-a=b). The use of enumerate and the odd list indexing is to exclude the current value, per the first sentence in this answer.
def do_they_add_alt(terms, result):
for i, term in enumerate(terms):
diff = result - term
if diff in [*terms[:i - 1], *terms[i + 1:]]:
return True
return False
If you do allow adding a number to itself, then the second implementation could be simplified to:
def do_they_add_alt(terms, result):
for term in terms:
diff = result - term
if diff in terms:
return True
return False
solution in javascript
this function takes 2 parameters and loop through the length of list and inside the loop there is another loop which adds one number to other numbers in the list and check there sum if its equal to k or not
const list = [10, 15, 3, 7];
const k = 17;
function matchSum(list, k){
for (var i = 0; i < list.length; i++) {
list.forEach(num => {
if (num != list[i]) {
if (list[i] + num == k) {
console.log(`${num} + ${list[i]} = ${k} (true)`);
}
}
})
}
}
matchSum(list, k);
My answer to Daily Coding Problem
# Python 2.7
def pairSumK (arr, goal):
return any(map(lambda x: (goal - x) in arr, arr))
arr = [10, 15, 3, 7]
print pairSumK(arr, 17)
Here is the code in Python 3.7 with O(N) complexity :
def findsome(arr,k):
if len(arr)<2:
return False;
for e in arr:
if k>e and (k-e) in arr:
return True
return False
and also best case code in Python 3.7 with O(N^2) complexity :
def findsomen2 (arr,k):
if len(arr)>1:
j=0
if arr[j] <k:
while j<len(arr):
i =0
while i < len(arr):
if arr[j]+arr[i]==k:
return True
i +=1
j +=1
return False
Javascript Solution
function matchSum(arr, k){
for( var i=0; i < arr.length; i++ ){
for(var j= i+1; j < arr.length; j++){
if (arr[i] + arr[j] === k){
return true;
}
}
}
return false;
}

I keep getting index out of range error what is wrong with my code?

My code won't run properly I am trying to get it to find peaks including the end and beginning of the array and then compare all the indexes that aren't the beginning or end to the index before and after them does anyone know why I am getting the out of index range error?
package main
import "fmt"
func linearFindPeaks(arg []int) []int {
peaks := []int{}
lenArg := len(arg)
for i := 0; i < lenArg; i++ {
//if its the first element run this
//second if statement for the end of array
// for default statements
if arg[0] > arg[1] {
peaks = append(peaks, arg[0])
} else if arg[lenArg-1] > arg[lenArg-2] {
peaks = append(peaks, arg[lenArg-1])
} else if arg[i] > arg[i+1] && arg[i] > arg[i-1] && arg[i] != arg[0] && arg[i] != arg[lenArg-1] {
peaks = append(peaks, arg[i])
}
}
fmt.Println(peaks)
return peaks
}
func main() {}
Playground: https://play.golang.org/p/2JRgEyRA50
Two possibilities i can see. Firstly, in the first else if:
}else if arg[lenArg - 1] > arg[lenArg -2] {
If lenArg is 1 then lenArg-2will be -1. This means arg[lenArg-2] is arg[-1] which will give you out of bounds.
Secondly, in the second else if:
} else if arg[i] > arg[i+1] ... {
On the last iteration over the loop, i will be lenArg-1, if you add 1 to this you'll get arg[lenArg-1+1] or arg[lenArg] which will out of bounds. (The last available index is at lenArg-1)
The Go Programming Language Specification
Index expressions
A primary expression of the form
a[x]
denotes the element of the slice a indexed by x.
The index x must be of integer type or untyped; it is in range if
0 <= x < len(a)
Otherwise it is out of range.
You need to pay attention to corner cases like lengths 0, 1, and 2 for indices i - 1, i, i + 1 out of range. For example,
package main
// For array a, a[i] is a peak if it is not smaller than its neighbor(s),
// where a[-1] = a[n] = -∞.
func findPeaks(a []int) []int {
var p []int
// special cases
if len(a) == 0 {
return p
}
if len(a) == 1 {
return append(p, a[0])
}
// first
i := 0
if a[i] >= a[i+1] {
p = append(p, a[i])
}
// first < i < last
for i = 1; i < len(a)-1; i++ {
if a[i-1] <= a[i] && a[i] >= a[i+1] {
p = append(p, a[i])
}
}
// last
i = len(a) - 1
if a[i-1] <= a[i] {
p = append(p, a[i])
}
return p
}
func main() {}
Playground: https://play.golang.org/p/9klj1wYnXZ

Resources