Two sum: Difference between revisions
m
→{{header|Wren}}: Changed to Wren S/H
(add RPL) |
m (→{{header|Wren}}: Changed to Wren S/H) |
||
(3 intermediate revisions by 3 users not shown) | |||
Line 1,055:
i = 1
j = len array[]
pair[] = [ ]
repeat
if array[i] + array[j] = sum
pair[] = [ i j ]
elif array[i] + array[j] > sum
j -= 1
Line 1,070 ⟶ 1,069:
.
numbers[] = [ 0 2 11 19 90 ]
print
</syntaxhighlight>
{{out}}
<pre>[ 2
=={{header|Elixir}}==
Line 3,041 ⟶ 3,040:
=={{header|V (Vlang)}}==
{{trans|Go}}
<syntaxhighlight lang="v (vlang)">
fn two_sum(a []int, target_sum int) (int, int, bool) {
len := a.len
if len < 2 {return 0, 0, false}
}▼
for i in 0..len - 1 {
if a[i] <= target_sum {
for j in i + 1..len {
sum := a[i] + a[j]
if sum == target_sum {return i, j, true}
if sum > target_sum
if sum > target_sum {▼
}
}
else
}▼
}
return 0, 0, false
Line 3,068 ⟶ 3,061:
target_sum := 21
p1, p2, ok := two_sum(a, target_sum)
else
}▼
} else {▼
</syntaxhighlight>▼
▲ println("The numbers with indices $p1 and $p2 sum to $target_sum")
}</syntaxhighlight>▼
{{out}}
Line 3,128 ⟶ 3,119:
=={{header|Wren}}==
<syntaxhighlight lang="
var c = a.count
if (c < 2) return []
Line 3,234 ⟶ 3,225:
<pre>The numbers with indices 2 and 4 sum to 21
---Program done, press RETURN---</pre>
=={{header|
'''Works with:''' 0.11.x, 0.12.0-dev.1389+42d4d07ef
const std = @import("std");▼
<syntaxhighlight lang="zig">pub fn sumsUpTo(comptime T: type, input: []const T, target_sum: T) ?struct { usize, usize } {
pub fn main() !void {▼
if (input.len <= 1) return null;
const array1 = [_]usize {0, 2, 11, 19, 90};▼
print("Result= [ {},{} ] \n", .{ Res.index1,Res.index2 })▼
▲}
return result: for (input[0 .. input.len - 1], 0..) |left, left_i| {
if (left > target_sum) break :result null;
if (current_sum < target_sum) continue;
if (current_sum == target_sum) break :result .{ left_i, right_i };
▲ for (a, 0..) |value1, j| {
▲}</syntaxhighlight>
▲ const sum1: usize = value + value1;
▲<syntaxhighlight lang="zig">const std = @import("std");
▲pub fn main() std.fs.File.WriteError!void {
const stdout =
const stdout_w = stdout.writer();
const stderr = std.io.getStdErr();
const stderr_w = stderr.writer();
const target_sum: u32 = 21;
const optional_indexes = sumsUpTo(u32, &a, target_sum);
if (optional_indexes) |indexes| {
try stderr_w.print("Numbers with sum {d} were not found!\n", .{target_sum});
▲ }
▲</syntaxhighlight>
{{Out}}
<pre>
</pre>
|