import org.scalatest.funsuite.AnyFunSuite import org.scalatest.flatspec.AnyFlatSpec import org.scalatest.matchers.should.Matchers import org.scalatest._ import flatspec._ class TestCases extends AnyFunSuite{ test("Bowls: (1,2,3,6), Dogs: (0,3) should return List(2,4)") { assert(FeedTheDogs.feedTheDogs(List(1,2,3,6), List(0,3)) == List(2,3)) } test("Bowls: (1,1,1,6,2,1), Dogs: (1,3) should return List(4,5)") { assert(FeedTheDogs.feedTheDogs(List(1,1,1,6,2,1), List(1,3)) == List(4,5)) } test("Bowls: (1,6,1), Dogs: (0,2) should return List(1,1)") { assert(FeedTheDogs.feedTheDogs(List(1,6,1), List(0,2)) == List(1,1)) } test("Bowls: (1,0,1,0,1), Dogs: (0,4) should return List(2,4)") { assert(FeedTheDogs.feedTheDogs(List(1,0,1,0,1), List(0,4)) == List(2,4)) } test("Bowls: (1,0,0,0,1), Dogs: (2,4) should return List(0,4)") { assert(FeedTheDogs.feedTheDogs(List(1,0,0,0,1), List(2,4)) == List(0,4)) } test("Bowls: (4,0,3,1,0), Dogs: (1,4) should return List(0,2)") { assert(FeedTheDogs.feedTheDogs(List(4,0,3,1,0), List(1,4)) == List(0,2)) } test("Bowls: (0,1,2,3,4), Dogs: (2,2) should return List(4,4)") { assert(FeedTheDogs.feedTheDogs(List(0,1,2,3,4), List(2,2)) == List(4,4)) } test("Bowls: (0,0,1,0,0), Dogs: (1,4) should return List(2,4)") { assert(FeedTheDogs.feedTheDogs(List(0,0,1,0,0), List(1,4)) == List(2,4)) } test("Bowls: (0,2,1,3,4), Dogs: (1,2,3) should return List(4,4,4)") { assert(FeedTheDogs.feedTheDogs(List(0,2,1,3,4), List(1,2,3)) == List(4,4,4)) } test("Bowls: (0,5,1,7,2), Dogs: (0,3,4) should return List(1,3,2)") { assert(FeedTheDogs.feedTheDogs(List(0,5,1,7,2), List(0,3,4)) == List(1,3,2)) } test("Bowls: (7,0,5,1,7,2), Dogs: (4,2,3) should return List(0,0,0)") { assert(FeedTheDogs.feedTheDogs(List(7,0,5,1,7,2), List(4,2,3)) == List(0,0,0)) } test("Bowls: (0,2,0,4,1,2), Dogs: (3,2,1) should return List(5,5,4)") { assert(FeedTheDogs.feedTheDogs(List(0,2,0,4,1,2), List(3,2,1)) == List(5,5,4)) } } class RandomTests extends AnyFunSuite{ import scala.util.Random import scala.collection.mutable.ListBuffer for (_ <- Range(0, 100)) { val amountFood = scala.util.Random.between(3, 100) val amountDogs = scala.util.Random.between(0, amountFood) val arrFood = ListBuffer[Int]() val arrDogs = ListBuffer[Int]() for (f <- Range(0, amountFood + 1)) { arrFood.append(scala.util.Random.between(0, 7)) } for (d <- Range(0, amountDogs + 1)) { arrDogs.append(scala.util.Random.between(0, amountFood)) } test(s"Bowls: ${arrFood.toList}, Dogs: ${arrDogs.toList} should return ${FeedTheDogsSolution.feedTheDogs(arrFood.toList, arrDogs.toList)}") { assert(FeedTheDogs.feedTheDogs(arrFood.toList, arrDogs.toList) == FeedTheDogsSolution.feedTheDogs(arrFood.toList, arrDogs.toList)) } } object FeedTheDogsSolution { import scala.collection.mutable.ArrayBuffer def feedTheDogs(food: List[Int], dogs: List[Int]): List[Int] = { val position: ArrayBuffer[Int] = ArrayBuffer() position.addAll(dogs) val foodArray: ArrayBuffer[Int] = ArrayBuffer() foodArray.addAll(food) var first: Boolean = true while (!checkEmpty(foodArray)) { for (i <- Range(0, position.length)) { val j = position(i) if (foodArray(j) > 0) foodArray(j) -= 1 else { val move = moveDogs(foodArray, i, first, position) if (move != position(i)) { position(i) = move foodArray(move) -= 1 } } first = false } } return position.toList } def closeDogs(position: ArrayBuffer[Int], dog: Int): Int = { var closestDog = Integer.MAX_VALUE var closest = Integer.MAX_VALUE position foreach { x => val dif = Math.abs(x - dog) if (dif != 0 && dif < closest) { closest = dif closestDog = x } else if (dif != 0 && dif == closest) { return dog } } closestDog } def moveDogs(food: ArrayBuffer[Int], i: Int, first: Boolean, position: ArrayBuffer[Int]): Int = { var r = position(i) var l = position(i) while (r < food.length - 1 || l > 0) { if (r < food.length - 1) r += 1 if (l > 0) l -= 1 if (food(r) > 0 && food(l) == 0) return r if (food(r) == 0 && food(l) > 0) return l if (food(r) > 0 && food(l) > 0) { val closestDog = closeDogs(position, position(i)) if (closestDog < position(i)) return r if (closestDog > position(i) || closestDog == Integer.MAX_VALUE) return l if (first) { for (j <- Range(0, i)) { if (position(j) > position(i)) return position(i) } return l } return position(i) } } position(i) } def checkEmpty(food: ArrayBuffer[Int]): Boolean = { food foreach (x => if (x != 0) return false) true } } }
- import org.scalatest.funsuite.AnyFunSuite
- import org.scalatest.flatspec.AnyFlatSpec
- import org.scalatest.matchers.should.Matchers
- import org.scalatest._
- import flatspec._
- class TestCases extends AnyFunSuite{
- test("Bowls: (1,2,3,6), Dogs: (0,3) should return List(2,4)") {
- assert(FeedTheDogs.feedTheDogs(List(1,2,3,6), List(0,3)) == List(2,3))
- }
- test("Bowls: (1,1,1,6,2,1), Dogs: (1,3) should return List(4,5)") {
- assert(FeedTheDogs.feedTheDogs(List(1,1,1,6,2,1), List(1,3)) == List(4,5))
- }
- test("Bowls: (1,6,1), Dogs: (0,2) should return List(1,1)") {
- assert(FeedTheDogs.feedTheDogs(List(1,6,1), List(0,2)) == List(1,1))
- }
- test("Bowls: (1,0,1,0,1), Dogs: (0,4) should return List(2,4)") {
- assert(FeedTheDogs.feedTheDogs(List(1,0,1,0,1), List(0,4)) == List(2,4))
- }
- test("Bowls: (1,0,0,0,1), Dogs: (2,4) should return List(0,4)") {
- assert(FeedTheDogs.feedTheDogs(List(1,0,0,0,1), List(2,4)) == List(0,4))
- }
- test("Bowls: (4,0,3,1,0), Dogs: (1,4) should return List(0,2)") {
- assert(FeedTheDogs.feedTheDogs(List(4,0,3,1,0), List(1,4)) == List(0,2))
- }
- test("Bowls: (0,1,2,3,4), Dogs: (2,2) should return List(4,4)") {
- assert(FeedTheDogs.feedTheDogs(List(0,1,2,3,4), List(2,2)) == List(4,4))
- }
- test("Bowls: (0,0,1,0,0), Dogs: (1,4) should return List(2,4)") {
- assert(FeedTheDogs.feedTheDogs(List(0,0,1,0,0), List(1,4)) == List(2,4))
- }
- test("Bowls: (0,2,1,3,4), Dogs: (1,2,3) should return List(4,4,4)") {
- assert(FeedTheDogs.feedTheDogs(List(0,2,1,3,4), List(1,2,3)) == List(4,4,4))
- }
- test("Bowls: (0,5,1,7,2), Dogs: (0,3,4) should return List(1,3,2)") {
- assert(FeedTheDogs.feedTheDogs(List(0,5,1,7,2), List(0,3,4)) == List(1,3,2))
- }
- test("Bowls: (7,0,5,1,7,2), Dogs: (4,2,3) should return List(0,0,0)") {
- assert(FeedTheDogs.feedTheDogs(List(7,0,5,1,7,2), List(4,2,3)) == List(0,0,0))
- }
- test("Bowls: (0,2,0,4,1,2), Dogs: (3,2,1) should return List(5,5,4)") {
- assert(FeedTheDogs.feedTheDogs(List(0,2,0,4,1,2), List(3,2,1)) == List(5,5,4))
- }
- }
- class RandomTests extends AnyFunSuite{
- import scala.util.Random
- import scala.collection.mutable.ListBuffer
for (_ <- Range(0, 500)) {- for (_ <- Range(0, 100)) {
- val amountFood = scala.util.Random.between(3, 100)
- val amountDogs = scala.util.Random.between(0, amountFood)
- val arrFood = ListBuffer[Int]()
- val arrDogs = ListBuffer[Int]()
- for (f <- Range(0, amountFood + 1)) {
- arrFood.append(scala.util.Random.between(0, 7))
- }
- for (d <- Range(0, amountDogs + 1)) {
- arrDogs.append(scala.util.Random.between(0, amountFood))
- }
/*test("Bowls: (1,6,1), Dogs: (0,2) should return List(1,1)") {assert(FeedTheDogs.feedTheDogs(List(1,6,1), List(0,2)) == List(1,1))}*/}}- test(s"Bowls: ${arrFood.toList}, Dogs: ${arrDogs.toList} should return ${FeedTheDogsSolution.feedTheDogs(arrFood.toList, arrDogs.toList)}") {
- assert(FeedTheDogs.feedTheDogs(arrFood.toList, arrDogs.toList) == FeedTheDogsSolution.feedTheDogs(arrFood.toList, arrDogs.toList))
- }
- }
- object FeedTheDogsSolution {
- import scala.collection.mutable.ArrayBuffer
- def feedTheDogs(food: List[Int], dogs: List[Int]): List[Int] = {
- val position: ArrayBuffer[Int] = ArrayBuffer()
- position.addAll(dogs)
- val foodArray: ArrayBuffer[Int] = ArrayBuffer()
- foodArray.addAll(food)
- var first: Boolean = true
- while (!checkEmpty(foodArray)) {
- for (i <- Range(0, position.length)) {
- val j = position(i)
- if (foodArray(j) > 0) foodArray(j) -= 1
- else {
- val move = moveDogs(foodArray, i, first, position)
- if (move != position(i)) {
- position(i) = move
- foodArray(move) -= 1
- }
- }
- first = false
- }
- }
- return position.toList
- }
- def closeDogs(position: ArrayBuffer[Int], dog: Int): Int = {
- var closestDog = Integer.MAX_VALUE
- var closest = Integer.MAX_VALUE
- position foreach { x =>
- val dif = Math.abs(x - dog)
- if (dif != 0 && dif < closest) {
- closest = dif
- closestDog = x
- } else if (dif != 0 && dif == closest) {
- return dog
- }
- }
- closestDog
- }
- def moveDogs(food: ArrayBuffer[Int], i: Int, first: Boolean, position: ArrayBuffer[Int]): Int = {
- var r = position(i)
- var l = position(i)
- while (r < food.length - 1 || l > 0) {
- if (r < food.length - 1) r += 1
- if (l > 0) l -= 1
- if (food(r) > 0 && food(l) == 0) return r
- if (food(r) == 0 && food(l) > 0) return l
- if (food(r) > 0 && food(l) > 0) {
- val closestDog = closeDogs(position, position(i))
- if (closestDog < position(i)) return r
- if (closestDog > position(i) || closestDog == Integer.MAX_VALUE) return l
- if (first) {
- for (j <- Range(0, i)) {
- if (position(j) > position(i)) return position(i)
- }
- return l
- }
- return position(i)
- }
- }
- position(i)
- }
- def checkEmpty(food: ArrayBuffer[Int]): Boolean = {
- food foreach (x => if (x != 0) return false)
- true
- }
- }
- }
import static org.junit.jupiter.api.Assertions.assertTrue; import static org.junit.jupiter.api.Assertions.assertEquals; import java.util.Arrays; import java.util.Random; import org.junit.jupiter.api.Test; class SolutionTest { @Test void testCase() { assertTrue(Arrays.equals(new int[]{2,3}, FeedTheDogs.solution(new int[]{1,2,3,6},new int[]{0,3}))); assertTrue(Arrays.equals(new int[]{4,5}, FeedTheDogs.solution(new int[]{1,1,1,6,2,1},new int[]{1,3}))); assertTrue(Arrays.equals(new int[]{1,1}, FeedTheDogs.solution(new int[]{1,6,1},new int[]{0,2}))); assertTrue(Arrays.equals(new int[]{2,4}, FeedTheDogs.solution(new int[]{1,0,1,0,1},new int[]{0,4}))); assertTrue(Arrays.equals(new int[]{0,4}, FeedTheDogs.solution(new int[]{1,0,0,0,1},new int[]{2,4}))); assertTrue(Arrays.equals(new int[]{0,2}, FeedTheDogs.solution(new int[]{4,0,3,1,0},new int[]{1,4}))); assertTrue(Arrays.equals(new int[]{4,4}, FeedTheDogs.solution(new int[]{0,1,2,3,4},new int[]{2,2}))); assertTrue(Arrays.equals(new int[]{2,4}, FeedTheDogs.solution(new int[]{0,0,1,0,0},new int[]{1,4}))); assertTrue(Arrays.equals(new int[]{4,4,4}, FeedTheDogs.solution(new int[]{0,2,1,3,4},new int[]{1,2,3}))); assertTrue(Arrays.equals(new int[]{1,3,2}, FeedTheDogs.solution(new int[]{0,5,1,7,2},new int[]{0,3,4}))); assertTrue(Arrays.equals(new int[]{0,0,0}, FeedTheDogs.solution(new int[]{7,0,5,1,7,2},new int[]{4,2,3}))); assertTrue(Arrays.equals(new int[]{5,5,4}, FeedTheDogs.solution(new int[]{0,2,0,4,1,2},new int[] {3,2,1}))); } static int[] append(int[] arr, int element) { final int N = arr.length; arr = Arrays.copyOf(arr, N + 1); arr[N] = element; return arr; } @Test public void randomTests() { Random random = new Random(); for (int trial = 1; trial <= 100; trial++) { int amountFood = random.nextInt(3,100); int amountDogs = random.nextInt(3); int[] arrFood = {}; int[] arrDogs = {}; for (int f=0; f<=amountFood; f++){ arrFood=append(arrFood, random.nextInt(6)); } for (int d=0; d<=amountDogs; d++){ arrDogs=append(arrDogs, random.nextInt(amountFood)); } System.out.println(Arrays.toString(arrFood)+"-Comida de Perros"); System.out.println(Arrays.toString(arrDogs)+"-Posicion de los Perros"); System.out.println(Arrays.toString(FeedTheDogs.solution(arrFood, arrDogs))+"--Supuesta Solucion\n"); assertEquals(solutionRandom(arrFood, arrDogs), FeedTheDogs.solution(arrFood, arrDogs)); } } public static int[] solutionRandom(int[] food, int[] dogs) { int[] position = dogs; boolean first = true; while (!checkEmpty(food)) { for (int i = 0; i < position.length; i++) { int j = position[i]; if (food[j] > 0) food[j]--; else { int move = moveDog(food, i, first, position); if (move != position[i]) { position[i] = move; food[move]--; } } first = false; } } return position; } public static int closeDog(int[] position, int dog) { int closestDog = Integer.MAX_VALUE; int closest = Integer.MAX_VALUE; for (int i : position) { int dif = Math.abs(i - dog); if (dif != 0 && dif < closest) { closest = dif; closestDog = i; } else if (dif != 0 && dif == closest) return dog; } return closestDog; } public static int moveDog(int[] food, int i, boolean first, int[] position) { int r = position[i]; int l= position[i]; while(r < food.length -1 || l > 0) { if(r < food.length-1 ) r++; if(l > 0) l--; if (food[r] > 0 && food[l] == 0) return r; if (food[r] == 0 && food[l] > 0) return l; if (food[r] > 0 && food[l] > 0) { int closestDog = closeDog(position, position[i]); if (closestDog < position[i])return r; if (closestDog > position[i] || closestDog == Integer.MAX_VALUE) return l; if (first) { for (int j = 0; j < i; j++) { if(position[j]>position[i])return position[i]; } return l; } return position[i]; } } return position[i]; } public static boolean checkEmpty(int[] food) { for (int f : food) { if (f != 0) return false; } return true; } }
- import static org.junit.jupiter.api.Assertions.assertTrue;
- import static org.junit.jupiter.api.Assertions.assertEquals;
- import java.util.Arrays;
- import java.util.Random;
- import org.junit.jupiter.api.Test;
- class SolutionTest {
- @Test
- void testCase() {
- assertTrue(Arrays.equals(new int[]{2,3}, FeedTheDogs.solution(new int[]{1,2,3,6},new int[]{0,3})));
- assertTrue(Arrays.equals(new int[]{4,5}, FeedTheDogs.solution(new int[]{1,1,1,6,2,1},new int[]{1,3})));
- assertTrue(Arrays.equals(new int[]{1,1}, FeedTheDogs.solution(new int[]{1,6,1},new int[]{0,2})));
- assertTrue(Arrays.equals(new int[]{2,4}, FeedTheDogs.solution(new int[]{1,0,1,0,1},new int[]{0,4})));
- assertTrue(Arrays.equals(new int[]{0,4}, FeedTheDogs.solution(new int[]{1,0,0,0,1},new int[]{2,4})));
- assertTrue(Arrays.equals(new int[]{0,2}, FeedTheDogs.solution(new int[]{4,0,3,1,0},new int[]{1,4})));
- assertTrue(Arrays.equals(new int[]{4,4}, FeedTheDogs.solution(new int[]{0,1,2,3,4},new int[]{2,2})));
- assertTrue(Arrays.equals(new int[]{2,4}, FeedTheDogs.solution(new int[]{0,0,1,0,0},new int[]{1,4})));
- assertTrue(Arrays.equals(new int[]{4,4,4}, FeedTheDogs.solution(new int[]{0,2,1,3,4},new int[]{1,2,3})));
- assertTrue(Arrays.equals(new int[]{1,3,2}, FeedTheDogs.solution(new int[]{0,5,1,7,2},new int[]{0,3,4})));
- assertTrue(Arrays.equals(new int[]{0,0,0}, FeedTheDogs.solution(new int[]{7,0,5,1,7,2},new int[]{4,2,3})));
- assertTrue(Arrays.equals(new int[]{5,5,4}, FeedTheDogs.solution(new int[]{0,2,0,4,1,2},new int[] {3,2,1})));
- }
- static int[] append(int[] arr, int element) {
- final int N = arr.length;
- arr = Arrays.copyOf(arr, N + 1);
- arr[N] = element;
- return arr;
- }
- @Test
- public void randomTests() {
- Random random = new Random();
- for (int trial = 1; trial <= 100; trial++) {
- int amountFood = random.nextInt(3,100);
- int amountDogs = random.nextInt(3);
- int[] arrFood = {};
- int[] arrDogs = {};
- for (int f=0; f<=amountFood; f++){
- arrFood=append(arrFood, random.nextInt(6));
- }
- for (int d=0; d<=amountDogs; d++){
- arrDogs=append(arrDogs, random.nextInt(amountFood));
- }
- System.out.println(Arrays.toString(arrFood)+"-Comida de Perros");
- System.out.println(Arrays.toString(arrDogs)+"-Posicion de los Perros");
- System.out.println(Arrays.toString(FeedTheDogs.solution(arrFood, arrDogs))+"--Supuesta Solucion\n");
- assertEquals(solutionRandom(arrFood, arrDogs), FeedTheDogs.solution(arrFood, arrDogs));
- }
- }
- public static int[] solutionRandom(int[] food, int[] dogs) {
- int[] position = dogs;
- boolean first = true;
- while (!checkEmpty(food)) {
- for (int i = 0; i < position.length; i++) {
- int j = position[i];
- if (food[j] > 0) food[j]--;
- else {
- int move = moveDog(food, i, first, position);
- if (move != position[i]) {
- position[i] = move;
- food[move]--;
- }
- }
- first = false;
- }
- }
- return position;
- }
- public static int closeDog(int[] position, int dog) {
- int closestDog = Integer.MAX_VALUE;
- int closest = Integer.MAX_VALUE;
- for (int i : position) {
- int dif = Math.abs(i - dog);
- if (dif != 0 && dif < closest) {
- closest = dif;
- closestDog = i;
- } else if (dif != 0 && dif == closest)
- return dog;
- }
- return closestDog;
- }
- public static int moveDog(int[] food, int i, boolean first, int[] position) {
- int r = position[i];
- int l= position[i];
- while(r < food.length -1 || l > 0) {
- if(r < food.length-1 ) r++;
- if(l > 0) l--;
- if (food[r] > 0 && food[l] == 0) return r;
- if (food[r] == 0 && food[l] > 0) return l;
- if (food[r] > 0 && food[l] > 0) {
- int closestDog = closeDog(position, position[i]);
- if (closestDog < position[i])return r;
- if (closestDog > position[i] || closestDog == Integer.MAX_VALUE) return l;
- if (first) {
- for (int j = 0; j < i; j++) {
- if(position[j]>position[i])return position[i];
- }
- return l;
- }
- return position[i];
- }
- }
- return position[i];
- }
- public static boolean checkEmpty(int[] food) {
- for (int f : food) {
- if (f != 0) return false;
- }
- return true;
- }
- }
fork dos
def pepito(chiqui):
return chiqui
import codewars_test as test
# TODO Write tests
import solution # or from solution import example
# test.assert_equals(actual, expected, [optional] message)
@test.describe("Example")
def test_group():
@test.it("test case")
def test_case():
test.assert_equals(1, 1)
You are given two collections: "plates" and "dogs". The array "plates" contains the number of servings there are in each plate, and the array "dogs" represents the position where the dogs start from.
The dogs will go to the closest plate to them, and will eat a serving of food until there's nothing left on theri plate. Each dog, after they'vs finished, will go to he next plate for more food. How do you determine which plate they're going to? here's the criteria:
- The'll go to the closest plate to them.
- If two plates are at the same distance from the dog, they'll go to plate farthest from the other dogs.
- They could eat any amount of dogs on the same plate, if theres enough food for all the dogs. If theres not enough food for all the dogs they go to the closest bowl.
- If theres no food left, the dogs stays where they are.
Notes:
- At most there can only be 6 servings of food per bowl
- The two colections they always gona be the same lenght
def feedTheDogs(food,dogs):
return dogsPosition
import codewars_test as test
# TODO Write tests
import solution # or from solution import example
# test.assert_equals(actual, expected, [optional] message)
@test.describe("Example")
def test_group():
@test.it("test case")
def test_case():
test.assert_equals(feedTheDogs([1,2,3,6],[0,3]),[2,3])
test.assert_equals(feedTheDogs([1,1,1,6,2,1],[1,3]),[4,5])
test.assert_equals(feedTheDogs([1,6,1,],[0,2]),[1,1])
test.assert_equals(feedTheDogs([1,0,1,0,1],[0,4]),[0,4])
test.assert_equals(feedTheDogs([1,0,0,0,1],[2,4]),[0,4])
test.assert_equals(feedTheDogs([4,0,3,1,0],[1,4]),[0,2])
You will be given a string that contains space-separated words. Your task is to group the words in this way:
- Group them by their beginning.
- Count how many letters they share in said group.
- Return the grouped words, ordered in ascending order, ONLY if their group size (or array length) is equal to the number of shared letters in each beginning.
See the following example:
"a abc abcd abe hi hello" -> ["a", "abc", "abcd", "abe"]
, ["abc", "abcd", "ab"]
, ["abc", "abcd"]
, ["abcd"]
, ["hi", "hello"]
See how we treat these arrays:
["a", "abc", "abcd", "abe"]
-> The size of this array is 4, yet they only share in the beginning "a". (1 letter) they don't match.
["abc", "abcd", "ab"]
-> The size of this array is 3, and they only share in the beginning "ab" (2 letters) they don't match.
["abc", "abcd"]
-> The size of this array is 2, only share in the beginning "abc" (3 letters), they don't match.
["abcd"]
-> The size of this array is 1, and they share in the beginning "abcd" (4 letters), they don't match.
["hi", "hello"]
-> The size of this array is 2, and they share in the beginning "h" (1 letter), they don't match.
NOTES:
- If 2 or more of the same word appear in the string, you should treat them as different words: Example: "is is" ->
["is", "is"]
-> The size of the array is 2, and both share the beginning "is" (2 letters) -> Should add it to the returned string. - If in the String any word has an UpperCase Char, you should transform the String into LowerCase.Example: "Or or" ->
["or, "or"]
- Some answers may time out so efficiency is key!
import re def letter(str): words = re.sub(r"[^a-z]", " ", str.lower()).split(" ") lst = [] l1 = [] l2 = [] sol = [] for x in words: word = "" for y in x: word += y lst.append(word) for x in sorted(set(lst)): for y in words: if y.startswith(x): l1.append(y) l2.append(list(l1)) l1.clear() dic = dict(zip(sorted(set(lst)), l2)) for k, v in dic.items(): if len(k) == len(v): for x in v: sol.append(x) return sorted(sol)
def letras(str):import re- import re
- def letter(str):
- words = re.sub(r"[^a-z]", " ", str.lower()).split(" ")
- lst = []
- l1 = []
- l2 = []
- sol = []
- for x in words:
- word = ""
- for y in x:
- word += y
- lst.append(word)
- for x in sorted(set(lst)):
- for y in words:
- if y.startswith(x):
- l1.append(y)
- l2.append(list(l1))
- l1.clear()
- dic = dict(zip(sorted(set(lst)), l2))
- for k, v in dic.items():
- if len(k) == len(v):
- for x in v:
- sol.append(x)
print(sol)return sol- return sorted(sol)
import codewars_test as test # TODO Write tests import re import random import solution # or from solution import example # test.assert_equals(actual, expected, [optional] message) @test.describe("Example") def test_group(): @test.it("test case") def test_case(): test.assert_equals(letter("a abc abcd abcde hey hello"), ["abc", "abcd", "abcde", "hello", "hey"]) test.assert_equals(letter("a abc abcd abe hi hello"), []) test.assert_equals(letter("Abc aBcd AbcDe"), ["abc", "abcd", "abcde"]) test.assert_equals(letter("this is all solution"), ["all", "is", "solution", "this"]) test.assert_equals(letter("only some solutions are answers"), ["only", "solutions", "some"]) test.assert_equals(letter("nothing is solution neither in string"), []) @test.describe("Random Tests") def random_tests(): def lettertest(str): words = re.sub(r"[^a-z]", " ", str.lower()).split(" ") lst = [] l1 = [] l2 = [] sol = [] for x in words: word = "" for y in x: word += y lst.append(word) for x in sorted(set(lst)): for y in words: if y.startswith(x): l1.append(y) l2.append(list(l1)) l1.clear() dic = dict(zip(sorted(set(lst)), l2)) for k, v in dic.items(): if len(k) == len(v): for x in v: sol.append(x) return sorted(sol) @test.it("Tests") def _(): for _ in range(100): source = "".join(random.choice("abcABC ") for _ in range(50)) words = "".join(random.choice(source) for _ in range(random.randrange(1, 30))) test.assert_equals(letter(words), lettertest(words), f"For letter({repr(words)})\n")
- import codewars_test as test
- # TODO Write tests
- import re
- import random
- import solution # or from solution import example
- # test.assert_equals(actual, expected, [optional] message)
- @test.describe("Example")
- def test_group():
- @test.it("test case")
- def test_case():
test.assert_equals(letras("why my wheat disappear, they need it for the theeme party."), ['the', 'theeme', 'they', 'wheat', 'why'])test.assert_equals(letras("If the icecream is not in the freezer, is going to be melted"), [])test.assert_equals(letras(""), [])test.assert_equals(letras("iii i iii aaa a uu u uu f o o a"), ['f'])test.assert_equals(letras("141234 129347 483743 1092374 4728349 12093487 ,,,....."), [])- test.assert_equals(letter("a abc abcd abcde hey hello"), ["abc", "abcd", "abcde", "hello", "hey"])
- test.assert_equals(letter("a abc abcd abe hi hello"), [])
- test.assert_equals(letter("Abc aBcd AbcDe"), ["abc", "abcd", "abcde"])
- test.assert_equals(letter("this is all solution"), ["all", "is", "solution", "this"])
- test.assert_equals(letter("only some solutions are answers"), ["only", "solutions", "some"])
- test.assert_equals(letter("nothing is solution neither in string"), [])
- @test.describe("Random Tests")
- def random_tests():
- def lettertest(str):
- words = re.sub(r"[^a-z]", " ", str.lower()).split(" ")
- lst = []
- l1 = []
- l2 = []
- sol = []
- for x in words:
- word = ""
- for y in x:
- word += y
- lst.append(word)
- for x in sorted(set(lst)):
- for y in words:
- if y.startswith(x):
- l1.append(y)
- l2.append(list(l1))
- l1.clear()
- dic = dict(zip(sorted(set(lst)), l2))
- for k, v in dic.items():
- if len(k) == len(v):
- for x in v:
- sol.append(x)
- return sorted(sol)
- @test.it("Tests")
- def _():
- for _ in range(100):
- source = "".join(random.choice("abcABC ") for _ in range(50))
- words = "".join(random.choice(source) for _ in range(random.randrange(1, 30)))
- test.assert_equals(letter(words), lettertest(words), f"For letter({repr(words)})\n")
You will be given a string that contains space-separated words. Your task is to group the words in this way:
- Group them by their beginning.
- Count how many letters they share in said group.
- Return the grouped words, ordered in ascending order, ONLY if their group size (or array length) is equal to the number of shared letters in each beginning.
See the following example:
"a abc abcd abe hi hello" -> ["a", "abc", "abcd", "abe"]
, ["abc", "abcd", "ab"]
, ["abc", "abcd"]
, ["abcd"]
, ["hi", "hello"]
See how we treat these arrays:
["a", "abc", "abcd", "abe"]
-> The size of this array is 4, yet they only share in the beginning "a". (1 letter) they don't match.
["abc", "abcd", "ab"]
-> The size of this array is 3, and they only share in the beginning "ab" (2 letters) they don't match.
["abc", "abcd"]
-> The size of this array is 2, only share in the beginning "abc" (3 letters), they don't match.
["abcd"]
-> The size of this array is 1, and they share in the beginning "abcd" (4 letters), they don't match.
["hi", "hello"]
-> The size of this array is 2, and they share in the beginning "h" (1 letter), they don't match.
NOTES:
- If 2 or more of the same word appear in the string, you should treat them as different words:
Example: "is is" ->["is", "is"]
-> The size of the array is 2, and both share the beginning "is" (2 letters) -> Should add it to the returned string. - If in the String any word has an UpperCase Char, you should transform the String into LowerCase.
Example: "Or or" ->["or, "or"]
- Some answers may time out so efficiency is key!
import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.Map; import java.util.TreeMap; import java.util.*; public class TreeJava { public static String[] solution(String str) { str=str.toLowerCase(); Map<String, Integer> t = new TreeMap<>(); String[] words = str.split("\\W"); List<String> sol = new ArrayList<>(); if(words.length==0) { return words; } int max = words[0].length(); for (String string : words) { if (max < string.length()) max = string.length(); } for (int i = 1; i < max; i++) { for (String string : words) { if (i <= string.length()) t.put(string.substring(0, i), i); } } for (Map.Entry<String, Integer> entry : t.entrySet()) { String key = entry.getKey(); Integer val = entry.getValue(); int cont = 0; List<String> l = new ArrayList<>(); for (String string : words) { if (string.startsWith(key)) { cont++; l.add(string); } } if (cont == val) sol.addAll(l); } String [] sol2 = sol.toArray(new String[sol.size()]); Arrays.sort(sol2); return sol2; } }
- import java.util.ArrayList;
import java.util.Comparator;- import java.util.Arrays;
- import java.util.List;
- import java.util.Map;
- import java.util.TreeMap;
- import java.util.*;
- public class TreeJava {
public static String[] solution(String str) {Map<String, Integer> t = new TreeMap<>();String[] words = str.split("[,. ]");List<String> sol = new ArrayList<>();int max = words[0].length();for (String string : words) {if (max < string.length())max = string.length();}for (int i = 1; i < max; i++) {for (String string : words) {if (i <= string.length())t.put(string.substring(0, i), i);}}for (Map.Entry<String, Integer> entry : t.entrySet()) {String key = entry.getKey();Integer val = entry.getValue();int cont = 0;List<String> l = new ArrayList<>();for (String string : words) {if (string.startsWith(key)) {cont++;l.add(string);}}if (cont == val)sol.addAll(l);}Comparator<String> compare=new Comparator<String>() {@Overridepublic int compare(String o1, String o2) {if(str.indexOf(o1)<str.indexOf(o2)) return -1;if(str.indexOf(o1)>str.indexOf(o2)) return 1;return 0;}};sol.sort(compare);System.out.println(sol.toString());return sol.toArray(new String[sol.size()]);}- public static String[] solution(String str) {
- str=str.toLowerCase();
- Map<String, Integer> t = new TreeMap<>();
- String[] words = str.split("\\W");
- List<String> sol = new ArrayList<>();
- if(words.length==0) {
- return words;
- }
- int max = words[0].length();
- for (String string : words) {
- if (max < string.length())
- max = string.length();
- }
- for (int i = 1; i < max; i++) {
- for (String string : words) {
- if (i <= string.length())
- t.put(string.substring(0, i), i);
- }
- }
- for (Map.Entry<String, Integer> entry : t.entrySet()) {
- String key = entry.getKey();
- Integer val = entry.getValue();
- int cont = 0;
- List<String> l = new ArrayList<>();
- for (String string : words) {
- if (string.startsWith(key)) {
- cont++;
- l.add(string);
- }
- }
- if (cont == val)
- sol.addAll(l);
- }
- String [] sol2 = sol.toArray(new String[sol.size()]);
- Arrays.sort(sol2);
- return sol2;
- }
- }
import static org.junit.jupiter.api.Assertions.assertTrue; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.Map; import java.util.TreeMap; import java.util.Arrays; import java.util.*; import static org.junit.jupiter.api.Assertions.assertEquals; import org.junit.jupiter.api.Test; class SolutionTest { @Test void test() { assertTrue(Arrays.equals(new String[]{"abc", "abcd", "abcde", "hello", "hey"}, TreeJava.solution("a abc abcd abcde hey hello"))); assertTrue(Arrays.equals(new String[]{}, TreeJava.solution("a abc abcd abe hi hello"))); assertTrue(Arrays.equals(new String[]{"abc", "abcd", "abcde"}, TreeJava.solution("Abc aBcd AbcDe"))); assertTrue(Arrays.equals(new String[]{"all", "is", "solution", "this"}, TreeJava.solution("this is all solution"))); assertTrue(Arrays.equals(new String[]{"only", "solutions", "some"}, TreeJava.solution("only some solutions are answers"))); assertTrue(Arrays.equals(new String[]{}, TreeJava.solution("nothing is solution neither in string"))); } private final String alphabet = "abcABC "; private final Random rand = new Random(); private char randomChar() { return alphabet.charAt(rand.nextInt(alphabet.length())); } @Test public void randomTests() { for (int trial = 1; trial <= 100; trial++) { String[] expected = new String[rand.nextInt(21)]; for (int i = 0; i < expected.length; i++) expected[i] = "" + randomChar() + randomChar(); if ( 0 < expected.length && rand.nextBoolean() ) expected[expected.length-1] = randomChar() + " "; StringBuilder sb = new StringBuilder(); for (int i = 0; i < expected.length; i++) sb.append(expected[i]); assertTrue(Arrays.equals(solutionTrue(sb.toString()), TreeJava.solution(sb.toString()))); } } public static String[] solutionTrue(String str) { str=str.toLowerCase(); Map<String, Integer> t = new TreeMap<>(); String[] words = str.split("\\W"); List<String> sol = new ArrayList<>(); if(words.length==0) { return words; } int max = words[0].length(); for (String string : words) { if (max < string.length()) max = string.length(); } for (int i = 1; i < max; i++) { for (String string : words) { if (i <= string.length()) t.put(string.substring(0, i), i); } } for (Map.Entry<String, Integer> entry : t.entrySet()) { String key = entry.getKey(); Integer val = entry.getValue(); int cont = 0; List<String> l = new ArrayList<>(); for (String string : words) { if (string.startsWith(key)) { cont++; l.add(string); } } if (cont == val) sol.addAll(l); } String [] sol2 = sol.toArray(new String[sol.size()]); Arrays.sort(sol2); return sol2; } }
- import static org.junit.jupiter.api.Assertions.assertTrue;
- import java.util.ArrayList;
- import java.util.Arrays;
- import java.util.List;
- import java.util.Map;
- import java.util.TreeMap;
- import java.util.Arrays;
- import java.util.*;
- import static org.junit.jupiter.api.Assertions.assertEquals;
- import org.junit.jupiter.api.Test;
- class SolutionTest {
- @Test
- void test() {
assertTrue(Arrays.equals(new String[]{"hola", "hoy", "me", "mal", "mañana", "mejor"}, TreeJava.solution("hola, hoy me encuentro mal,mañana estare mejor")));assertTrue(Arrays.equals(new String[]{"Hola", "hoy","encuentro", "encontrado", "encuesta"}, TreeJava.solution("Hola hoy, encuentro encontrado encuesta,persona,pareja")));}- assertTrue(Arrays.equals(new String[]{"abc", "abcd", "abcde", "hello", "hey"}, TreeJava.solution("a abc abcd abcde hey hello")));
- assertTrue(Arrays.equals(new String[]{}, TreeJava.solution("a abc abcd abe hi hello")));
- assertTrue(Arrays.equals(new String[]{"abc", "abcd", "abcde"}, TreeJava.solution("Abc aBcd AbcDe")));
- assertTrue(Arrays.equals(new String[]{"all", "is", "solution", "this"}, TreeJava.solution("this is all solution")));
- assertTrue(Arrays.equals(new String[]{"only", "solutions", "some"}, TreeJava.solution("only some solutions are answers")));
- assertTrue(Arrays.equals(new String[]{}, TreeJava.solution("nothing is solution neither in string")));
- }
- private final String alphabet = "abcABC ";
- private final Random rand = new Random();
- private char randomChar() {
- return alphabet.charAt(rand.nextInt(alphabet.length()));
- }
- @Test
- public void randomTests() {
- for (int trial = 1; trial <= 100; trial++) {
- String[] expected = new String[rand.nextInt(21)];
- for (int i = 0; i < expected.length; i++)
- expected[i] = "" + randomChar() + randomChar();
- if ( 0 < expected.length && rand.nextBoolean() )
- expected[expected.length-1] = randomChar() + " ";
- StringBuilder sb = new StringBuilder();
- for (int i = 0; i < expected.length; i++)
- sb.append(expected[i]);
- assertTrue(Arrays.equals(solutionTrue(sb.toString()), TreeJava.solution(sb.toString())));
- }
- }
- public static String[] solutionTrue(String str) {
- str=str.toLowerCase();
- Map<String, Integer> t = new TreeMap<>();
- String[] words = str.split("\\W");
- List<String> sol = new ArrayList<>();
- if(words.length==0) {
- return words;
- }
- int max = words[0].length();
- for (String string : words) {
- if (max < string.length())
- max = string.length();
- }
- for (int i = 1; i < max; i++) {
- for (String string : words) {
- if (i <= string.length())
- t.put(string.substring(0, i), i);
- }
- }
- for (Map.Entry<String, Integer> entry : t.entrySet()) {
- String key = entry.getKey();
- Integer val = entry.getValue();
- int cont = 0;
- List<String> l = new ArrayList<>();
- for (String string : words) {
- if (string.startsWith(key)) {
- cont++;
- l.add(string);
- }
- }
- if (cont == val)
- sol.addAll(l);
- }
- String [] sol2 = sol.toArray(new String[sol.size()]);
- Arrays.sort(sol2);
- return sol2;
- }
- }
Our job is to obtain all the words where the letters at begining are the same, but only the amount of words as letters are the same.
Example:
"why my wheat disappear, they need it for the theeme party."
['the', 'theeme', 'they', 'wheat', 'why']
In this case we have they
,the
,theeme
wich they start with t
, h
, e
.
The word in the String must be treated as all letters in lowercase and must count only alphametic letters, you must return the words in the colection in alphabetic order.
Then you have to return a collection of the words following the rules.
def letras(str): import re words = re.sub(r"[^a-z]", " ", str.lower()).split(" ") lst = [] l1 = [] l2 = [] sol = [] for x in words: word = "" for y in x: word += y lst.append(word) for x in sorted(set(lst)): for y in words: if y.startswith(x): l1.append(y) l2.append(list(l1)) l1.clear() dic = dict(zip(sorted(set(lst)), l2)) for k, v in dic.items(): if len(k) == len(v): for x in v: sol.append(x) print(sol) return sol
- def letras(str):
return ["mejorate", "hola", "ho","esto","estas","estreñido"]- import re
- words = re.sub(r"[^a-z]", " ", str.lower()).split(" ")
- lst = []
- l1 = []
- l2 = []
- sol = []
- for x in words:
- word = ""
- for y in x:
- word += y
- lst.append(word)
- for x in sorted(set(lst)):
- for y in words:
- if y.startswith(x):
- l1.append(y)
- l2.append(list(l1))
- l1.clear()
- dic = dict(zip(sorted(set(lst)), l2))
- for k, v in dic.items():
- if len(k) == len(v):
- for x in v:
- sol.append(x)
- print(sol)
- return sol
import codewars_test as test # TODO Write tests import solution # or from solution import example # test.assert_equals(actual, expected, [optional] message) @test.describe("Example") def test_group(): @test.it("test case") def test_case(): test.assert_equals(letras("why my wheat disappear, they need it for the theeme party."), ['the', 'theeme', 'they', 'wheat', 'why']) test.assert_equals(letras("If the icecream is not in the freezer, is going to be melted"), []) test.assert_equals(letras(""), []) test.assert_equals(letras("iii i iii aaa a uu u uu f o o a"), ['f']) test.assert_equals(letras("141234 129347 483743 1092374 4728349 12093487 ,,,....."), [])
- import codewars_test as test
- # TODO Write tests
- import solution # or from solution import example
- # test.assert_equals(actual, expected, [optional] message)
- @test.describe("Example")
- def test_group():
- @test.it("test case")
- def test_case():
test.assert_equals(letras("Hola, ho esto... estas estreñido, mejorate"), ["mejorate", "hola", "ho","esto","estas","estreñido"])- test.assert_equals(letras("why my wheat disappear, they need it for the theeme party."), ['the', 'theeme', 'they', 'wheat', 'why'])
- test.assert_equals(letras("If the icecream is not in the freezer, is going to be melted"), [])
- test.assert_equals(letras(""), [])
- test.assert_equals(letras("iii i iii aaa a uu u uu f o o a"), ['f'])
- test.assert_equals(letras("141234 129347 483743 1092374 4728349 12093487 ,,,....."), [])
Dado una string de palabras, almacenar todas aquellas palabras repetidas igual a la cantidad de letras iniciales con las que comiencen.
Ejemplo: "Hola, ho esto... estas estreñido, mejorate"
En el ejemplo mostrado guardaria esto, estas y estreñido por empezar las tres palabras con "e" "s" "t"
tres letras repetidas tres palabras.
Lo mismo con Hola y ho, ademas de mejorate que al ser una sola palabra que empiece con la m
def letras(str):
return ["mejorate", "hola", "ho","esto","estas","estreñido"]
import codewars_test as test
# TODO Write tests
import solution # or from solution import example
# test.assert_equals(actual, expected, [optional] message)
@test.describe("Example")
def test_group():
@test.it("test case")
def test_case():
test.assert_equals(letras("Hola, ho esto... estas estreñido, mejorate"), ["mejorate", "hola", "ho","esto","estas","estreñido"])